2016-09-14 67 views
0

我正在设计一个带有ggplot2包的条形图。 唯一的问题是,我无法摆脱酒吧和X轴之间的空间。 我知道这个公式应该解决这个问题:连续位置比例尺对ggplot2中条和x轴之间的间距没有影响R

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

但似乎对错误栏中的元素被覆盖,并总是给这个空间。

这里我的代码:

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)) 
+0

你能不能做一个重复的例子?可能你可以在内置的数据集上演示这个,但是如果不是,你应该用'dput()'或者通过模拟来分享你的数据。 [请参阅这里了解制作可重复示例的技巧](http://stackoverflow.com/q/5963269/903061)。 – Gregor

+0

此外,它很好,如果例子*最小* - 有助于消除分心的东西,从实际问题。如果自定义颜色,标签,角度文本,主题自定义等不属于问题的一部分,请将其从您的问题中删除。 – Gregor

+0

通过使用expand = c(0,0),可以将y轴的极限值设置为数据集中最大和最小y值。如果你的错误条可能非常大以至于它们低于零(奇怪但可能),那么最小值就是这个值(例如-1),而不是零。也许尝试并添加,限制= c(0,0)scale_y_continuous – Wave

回答

0

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

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") 

enter image description here

有从零点在y轴(杆的底部),并且其中x轴标签是一间隙。

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)) 

这让剧情:

enter image description here

注意我

为此,可以使用scale_y_discretescale_y_continuous,取决于您的数据的性质,并设置expandc(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)) 

enter image description here

你可以用规模来降低去除填充到错误吧:

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)) 

enter image description here

或者您可以使用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)) 

enter image description here

+0

是的,谢谢你作为一个例子显示的情节。我也可以获得这个结果,但是一旦我添加了错误栏,间距就会再次出现。 –

+0

我已经添加了一些错误栏。这是否突出(并解决)你遇到的问题? –

+0

是的,这完全突出了我的问题。我试图在最后添加scale_y_continuous(expand = c(0,0)),就像你做的那样,它终于按预期工作了!非常感谢你。 –

相关问题