连续位置刻度,对带有 R 的 ggplot2 中条形图和 x 轴之间的间距没有影响

Continuous position scales with no effect on the spacing between the bar and the x axis in ggplot2 with R

我正在用 ggplot2 包设计条形图。 唯一的问题是我无法摆脱条形图和 x 轴之间的 space。 我知道这个公式应该可以解决问题:

scale_y_continuous(expand = c(0, 0)) function 

但似乎错误栏的元素正在覆盖它并始终给出这个 space。

这里是我的代码:

p<-ggplot(data=tableaumergectrlmut, aes(x=ID, y=meanNSAFbait,  fill=Condition)) + 
geom_bar(stat="identity", position=position_dodge())+
scale_y_continuous(expand = c(0,0))+ 
geom_errorbar(aes(ymin=meanNSAFbait-SDNSAFbait, 
  ymax=meanNSAFbait+SDNSAFbait, width=0.25), position=position_dodge(.9))

使用一些示例数据生成一个图(我认为)显示您遇到的问题。

library(ggplot2)

df <- data.frame(val = c(10, 20, 100, 5), name = LETTERS[1:4])

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity")

从 y 轴(条的底部)上的零点到 x 轴标签所在的位置有一个间隙。

您可以使用 scale_y_discretescale_y_continuous 删除它,具体取决于数据的性质,并将 expand 设置为 c(0,0):

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  scale_y_discrete(expand = c(0,0)) + 
  scale_x_discrete(expand = c(0,0))

这给出了情节:

请注意,我还删除了沿 y 轴的间隙,只需删除 scale_x_discrete 线即可将此间隙添加回去。

由于误差线是一个问题,这里有几个例子:

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = val - 10,
                    ymax = val + 10))

您可以使用缩放将填充删除到误差线:

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = val - 10,
                    ymax = val + 10)) +
  scale_y_continuous(expand = c(0,0))

或者你可以用coord_cartesian硬截断:

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = val - 10,
                    ymax = val + 10)) +
  scale_y_continuous(expand = c(0,0)) +
  coord_cartesian(ylim = c(0, max(df$val) + 10))