简体   繁体   中英

Adjusting distance between groups of bars in ggplot2

This is my data:

> 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  

This is my code:

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

This is the output:

在此输入图像描述

However, I want to have Black+Red+Blue really close, then a space and then Black+Red+Blue really close again.

Thank you!

I think this is easiest to achieve if you use x = Time and fill = Group . Something like:

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

在此输入图像描述

Plot against Time only, then position_dodge has meaning for the bars (there are 3 observations per group). Use position_dodge with width close to the bar width. Add group=Group to make the errorbars behave like the bars (you need it since they don't have colour aesthetic to distinguish them). Use the same position_dodge width as before to align them properly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM