【问题标题】:How to change the space between bars in geom_bar?如何更改geom_bar中条之间的空间?
【发布时间】:2014-03-31 08:56:26
【问题描述】:

我有一个两边都是正值的条形图。当我更改条的宽度时,它们之间的空间变得很大并且看起来不太好。我试图用position = position_dodge 来操纵它,但它不起作用。如何减少条之间的空间?

这是包含我的数据的代码(最初发布在这里Stacked barplot crossing the x-axis):

Year <- factor(c("2003-2009","2003-2009","2003-2009","2003-2009","2003-2009","2009-2012",
              "2009-2012","2009-2012","2009-2012","2009-2012"))
Q <- c(.05,.25,.5,.75,.95)
Score <- c(6,6,4,3,1,23,20,19,24,32)
df <- data.frame(Year, Q, Score)

df <- transform(df, Score=ifelse(as.character(Year) %in% c("2003-2009"), -Score, Score))
df.split <- split(df, df$Score < 0)

ggplot() + 
  geom_bar(data=df.split[[1]],aes(x=Q, y=Score, fill=Year), stat="identity",width = 0.09)+
  geom_bar(data=df.split[[2]],aes(x=Q, y=Score, fill=Year), stat="identity",width = 0.09)+
  geom_hline(yintercept=0) +
  coord_flip()+
  scale_y_continuous(labels=abs,limits=c(-40,40))+ 
  theme_bw()+
  scale_x_continuous(breaks=c(.05,.25,.5,.75,.95))

【问题讨论】:

    标签: r ggplot2 space geom-bar


    【解决方案1】:

    Q 变量视为一个因素将设置条之间的间距相等。通常,当您减少条形的width 时,条形之间的空间会增加。但是,您需要窄条和条之间的小空间。您可以通过更改保存图像的height 来实现。

    代码(我还稍微更改了条形的width 和 y 轴的刻度):

    ggplot() + 
      geom_bar(data=df.split[[1]],aes(x=as.factor(Q), y=Score, fill=Year), stat="identity", width = 0.4) +
      geom_bar(data=df.split[[2]],aes(x=as.factor(Q), y=Score, fill=Year), stat="identity", width = 0.4) +
      geom_hline(yintercept=0) +
      coord_flip() +
      scale_y_continuous(labels=abs,limits=c(-10,35)) + 
      theme_bw() +
      ggsave("myplot.png", width=8, height=2, dpi=300)
    

    结果:

    请注意,我还删除了绘图代码的 scale_x_continuous(breaks=c(.05,.25,.5,.75,.95)) 部分,因为在将 Q 视为因子变量时会出错。

    【讨论】:

    • 感谢您的建议,但我一直想知道如何在不改变条形宽度的情况下减少空间。
    • 如果我理解正确,您需要窄条和条之间的小空间。我更新了我的答案。这会给你想要的结果吗?
    • 谢谢。我还在代码末尾尝试了“scale_x_discrete (expand = C (0,1.5))”。它还减少了条之间的空间,但在最低条下方和最高条上方留下了太多空间。
    • 这就是我选择在ggsave 代码中设置绘图尺寸的原因。如果答案对您有用,如果您接受答案(和/或给答案投票),我们将不胜感激。这将为未来的读者提供有关解决方案价值的线索。另请参阅此帮助页面:What should I do when someone answers my question?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2012-12-05
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多