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

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

问题描述

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


(x =因子(LETTERS [1:4]),y =样本(1:100,4))
$ b

  df < -  data.frame $ b 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()

宽度的以下其他设置进行比较:





到目前为止,太好了。现在,假设我们有两个因素。如果你想玩均匀间隔并列的条(例如在空格旁边的= TRUE 中使用 barplot()),使用 geom_bar(position =dodge)并不那么容易:您可以更改条宽,但不能在相邻栏之间添加空间(并且我没有在Google上找到方便的解决方案)。我结束了类似的事情:

  df < -  data.frame(g = gl(2,1,labels =字母[1:2]),y =样本(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 = (x = c(sum(x.seq [1:2])/ 2,sum(x.seq),y =)+
scale_x_discrete(breaks = NA)+
geom_text [3:4])/ 2),y = 0,
label = c(X,Y)),vjust = 1.2,size = 8)

用于$ x $ -axis的向量在data.frame中是注入的,所以如果你想要改变外部间距,而 width 允许控制内部间距。使用 scale_x_discrete()可以增强$ x $ -axis的标签。

https://i.stack.imgur.com/BoUeM.pngalt =alt text>


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

解决方案

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

Compare with the following other settings for width:

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)

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天全站免登陆