调整ggplot2中条形组之间的距离

时间:2014-02-14 07:01:50

标签: r ggplot2

这是我的数据:

> sum.ex  
        Timepoint     mean  n       sd Time   Group  
A1             A1-All 1.985249 26 1.000180   A1     All  
A1-pT2D       A1-pT2D 1.913109 13 1.012633   A1    pT2D  
A1-Control A1-Control 2.934105 13 2.472951   A1 Control  
B1             B1-All 2.555601 25 1.939970   B1     All  
B1-pT2D       B1-pT2D 2.057389 13 1.023416   B1    pT2D  
B1-Control B1-Control 2.145555 12 1.089522   B1 Control  

这是我的代码:

png('ex')  
ggplot(sum.ex, aes(x = Timepoint, y = mean)) +  
   geom_bar(width = 0.5, position = position_dodge(width = 200), stat="identity", aes(fill =     Group)) +  
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), size = 1, shape = 1, width = 0.2) +  
  scale_fill_manual(values = c("#333333", "#FF0000", "#0000FF")) +  
   xlab(NULL) +
  ggtitle("PLIN1") + theme_bw() + theme(panel.grid.major = element_blank())   
 dev.off()

这是输出:

enter image description here

然而,我想让Black + Red + Blue真的很近,然后一个空格然后Black + Red + Blue再次关闭。

谢谢!

2 个答案:

答案 0 :(得分:4)

如果您使用x = Timefill = Group,我认为这是最容易实现的。类似的东西:

dodge <- position_dodge(width = 0.5)
ggplot(df, aes(x = Time, y = mean, fill = Group)) +  
  geom_bar(width = 0.5, stat="identity", position = dodge) +  
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd),
                position = dodge, size = 1, shape = 1, width = 0.2) +  
  scale_fill_manual(values = c("#333333", "#FF0000", "#0000FF")) +
  theme_bw() +
  theme(panel.grid.major = element_blank())

enter image description here

答案 1 :(得分:3)

仅对Time进行绘图,然后position_dodge对条形有意义(每组有3个观察值)。使用宽度接近条宽的position_dodge。添加group=Group以使错误栏的行为与条形图一样(您需要它,因为它们没有颜色审美以区分它们)。使用与以前相同的position_dodge宽度来正确对齐它们。

ggplot(sum.ex, aes(x = Time, y = mean)) +  
  geom_bar(width = 0.5, position = position_dodge(width = 0.5), stat = "identity", aes(fill = Group)) +
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd, group=Group), position=position_dodge(width = 0.5), size = 1, shape = 1, width = 0.2) +  
  scale_fill_manual(values = c("#333333", "#FF0000", "#0000FF")) +  
  xlab(NULL) +
  ggtitle("PLIN1") + theme_bw() + theme(panel.grid.major = element_blank())