如何增加ggplot2中条形图中条形之间的空间? [英] How to increase the space between the bars in a bar plot in ggplot2?

查看:28
本文介绍了如何增加ggplot2中条形图中条形之间的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何增加 ggplot2 中条形图中条形之间的间距?

How can I increase the space between the bars in a bar plot in ggplot2 ?

推荐答案

你可以随时玩width参数,如下图:

You can always play with the width parameter, as shown below:

df <- data.frame(x=factor(LETTERS[1:4]), y=sample(1:100, 4))
library(ggplot2)
ggplot(data=df, aes(x=x, y=y, width=.5)) + 
  geom_bar(stat="identity", position="identity") +
  opts(title="width = .5") + labs(x="", y="") +
  theme_bw()

与以下其他width设置对比:

到目前为止,一切都很好.现在,假设我们有两个因素.如果您想使用均匀分布的并列条(例如在 barplot() 中将 spacebeside=TRUE 一起使用时),它是使用 geom_bar(position="dodge") 不是那么容易:您可以更改条形宽度,但不能在相邻条形之间添加空间(我在 Google 上没有找到方便的解决方案).我最终得到了这样的结果:

So far, so good. Now, suppose we have two factors. In case you would like to play with evenly spaced juxtaposed bars (like when using space together with beside=TRUE in barplot()), it's not so easy using geom_bar(position="dodge"): you can change bar width, but not add space in between adjacent bars (and I didn't find a convenient solution on Google). I ended up with something like that:

df <- data.frame(g=gl(2, 1, labels=letters[1:2]), y=sample(1:100, 4))
x.seq <- c(1,2,4,5)
ggplot(data=transform(df, x=x.seq), aes(x=x, y=y, width=.85)) +
  geom_bar(stat="identity", aes(fill=g)) + labs(x="", y="") + 
  scale_x_discrete(breaks = NA) + 
  geom_text(aes(x=c(sum(x.seq[1:2])/2, sum(x.seq[3:4])/2), y=0, 
                label=c("X","Y")), vjust=1.2, size=8)

用于 $x$ 轴的向量在 data.frame 中注入",因此您可以根据需要更改外部间距,而 width 允许控制内部间距.可以使用 scale_x_discrete() 增强 $x$ 轴的标签.

The vector used for the $x$-axis is "injected" in the data.frame, so that so you change the outer spacing if you want, while width allows to control for inner spacing. Labels for the $x$-axis might be enhanced by using scale_x_discrete().

这篇关于如何增加ggplot2中条形图中条形之间的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆