为什么 ggplot2 geom_col 将离散 x 轴标签误读为连续?
目标:绘制代表离散站点浓度值的柱形图
问题:14 个站点标签是数字,因此我认为 ggplot2 假设连续数据并为它认为的“缺失数字”添加空格。相对于数据框中的 14 个值,我只需要 14 列和 14 个标记/标签。我尝试将站点指定为因素和字符,但都不起作用。
另外,如何确保 y 轴以“0”结束,以便列的底部与 x 轴相交?
感谢
数据:
Sites: 2,4,6,7,8,9,10,11,12,13,14,15,16,17
Concentration: 10,16,3,15,17,10,11,19,14,12,14,13,18,16
Aim: plot a column chart representing concentration values at discrete sites
Problem: the 14 site labels are numeric, so I think ggplot2 is assuming continuous data and adding spaces for what it sees as 'missing numbers'. I only want 14 columns with 14 marks/labels, relative to the 14 values in the dataframe. I've tried assigning the sites as factors and characters but neither work.
Also, how do you ensure the y-axis ends at '0', so the bottom of the columns meet the x-axis?
Thanks
Data:
Sites: 2,4,6,7,8,9,10,11,12,13,14,15,16,17
Concentration: 10,16,3,15,17,10,11,19,14,12,14,13,18,16
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有两个问题合而为一,有两个非常简单的答案:
1。当您的列是连续列时,如何强制使用离散轴?要使 ggplot2 绘制离散轴,数据必须是离散的。您可以通过转换为因子来强制数字数据离散。因此,请使用
x=as.factor(Sites)
,而不是绘图代码中的x=Sites
。2.如何消除柱形图中柱下方的空白?您可以通过
scale_y_continuous()
函数控制y
轴的限制。默认情况下,限制超出实际数据一点(在本例中,从 0 到最大浓度)。您可以通过expand=
参数覆盖该行为。有关更多详细信息,请查看expansion()
的文档,但这里我将使用mult=
,它使用乘法来根据数据查找新的限制。我使用0
作为下限,使轴下限等于数据中的最小值 (0
),并使用0.05
作为上限将图表限制扩大到超过最大值约 5%(我相信这是默认值)。这是代码和结果图。
You have two questions in one with two pretty straightforward answers:
1. How to force a discrete axis when your column is a continuous one? To make
ggplot2
draw a discrete axis, the data must be discrete. You can force your numeric data to be discrete by converting to a factor. So, instead ofx=Sites
in your plot code, usex=as.factor(Sites)
.2. How to eliminate the white space below the columns in a column plot? You can control the limits of the
y
axis via thescale_y_continuous()
function. By default, the limits extend a bit past the actual data (in this case, from 0 to the max Concentration). You can override that behavior via theexpand=
argument. Check the documentation forexpansion()
for more details, but here I'm going to usemult=
, which uses a multiplication to find the new limits based on the data. I'm using0
for the lower limit to make the lower axis limit equal the minimum in your data (0
), and0.05
as the upper limit to expand the chart limits about 5% past the max value (this is default, I believe).Here's the code and resulting plot.