在ggplot2中增加条形图之间的空间

47
我想在ggplot2中的条形图之间添加空格。这个页面提供了一个解决方案:http://www.streamreader.org/stats/questions/6204/how-to-increase-the-space-between-the-bars-in-a-bar-plot-in-ggplot2。然而,与使用x轴分组的因子级别不同,这个解决方案创建了一个数字序列x.seq,手动放置条形并使用width()参数进行缩放。width()在像下面的例子中使用x轴因子级别分组时无法工作。
library(ggplot2)

Treatment <- rep(c('T','C'),each=2)
Gender <- rep(c('M','F'),2)
Response <- sample(1:100,4)
df <- data.frame(Treatment, Gender, Response)

hist <- ggplot(df, aes(x=Gender, y=Response, fill=Treatment, stat="identity"))
hist + geom_bar(position = "dodge") + scale_y_continuous(limits = c(0, 
    100), name = "") 

有人知道如何在使用因子级别分组时获得与链接示例相同的效果吗?


1
另外值得注意的是,分面绘图 + facet_grid(~Treatment) 的实用性。 - Brandon Bertelsen
1个回答

96

这是否是您想要的?

hist + geom_bar(width=0.4, position = position_dodge(width=0.5))
  • geom_bar中的width决定了条形图的宽度。
  • position_dodge中的width决定了每个条形的位置。

也许你在使用一段时间后就可以轻松理解它们的行为。

enter image description here


5
在现代 ggplot2(>= 2.1.0)中,geom_histogram() 中的 width 已被弃用。 - krlmlr
14
如果我想让每组的条形图保持在一起(例如这里的“C”和“T”条形图),但是想要改变组之间的间距(这里的“M”和“F”)怎么办? - user5359531
2
关于用户5359531的问题,请参见此处:https://dev59.com/plQK5IYBdhLWcg3wbPP7 - Kastany
2
由于kohske没有描述它们的工作原理:geom_bar中的width是x轴条形图组的宽度。position_dodge中的width是每个x轴组内条形图的宽度。宽度为“1”表示条形图/组彼此相接触。宽度小于1会在条形图或组之间添加空间。 - GMSL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接