2013-04-09 177 views
1

本质:堆叠多个列上geom_bar在GGPLOT2

  1. 我想画一个柱状图,显示两个表列,这是我设法用做聚合值: err.bar <- ggplot(ss.data, aes(x=pop, y=obs+proc)) err.bar <- err.bar + geom_bar(position="stack", stat = "identity") err.bar

  2. 我想阴影,不一定是颜色,聚合酒吧的两个部分。

  3. 最后,我想通过根据物种将它们分组

我的数据(即,通过物种Ë& C对上的Excel图表的x轴标签所指示的)来着色条使用类似于:

  • 弹出E1 E2 E3 E4 E5 E6 E7 C1 C2 C3 C4
  • OBS 0.0027 0.0018 0.0464 0.0095 0.0034 0.0117 0.017 0.1178 0.0449 0.039 0.0903
  • PROC 0.0319 0.0196 0.0511 0.0143 0.0048 0.0078 0.0396 0.1662 0.074 0.1681 0.1358

回答

3

这里是让你最想要什么样的解决方案。但请注意,ggplot的设计不允许在单个绘图中分别设置“阴影”和“颜色”参数。相反,我使用灰色填充颜色为您的obsproc类别着色,并且我已将物种分组为多个分面(而不是以不同的颜色着色)。

library(ggplot2) 
library(reshape2) 

ss.data = data.frame(
    pop=c("E1", "E2", "E3", "E4", "E5", "E6", "E7", "C1", "C2", "C3", "C4"), 
    obs=c(0.0027, 0.0018, 0.0464, 0.0095, 0.0034, 0.0117, 0.017, 0.1178, 
      0.0449, 0.039, 0.0903), 
    proc=c(0.0319, 0.0196, 0.0511, 0.0143, 0.0048, 0.0078, 0.0396, 0.1662, 
      0.074, 0.1681, 0.1358), stringsAsFactors=FALSE) 

# Add new column 'species' by removing the trailing digits from 'pop'. 
ss.data$species = gsub("\\d", "", ss.data$pop) 

# Convert data to long-form with 'melt' from the reshape2 package. 
mdat = melt(ss.data, id.vars=c("pop", "species"), 
      measure.vars=c("obs", "proc")) 

plot_1 = ggplot(mdat, aes(x=pop, y=value, fill=variable)) + 
     theme_bw() + 
     geom_bar(position="stack", stat="identity") + 
     scale_fill_manual(values=c("grey50", "grey80")) + 
     facet_grid(. ~ species, space="free_x", scales="free_x", 
      labeller=label_both) 

ggsave("plot_1.png", plot=plot_1, width=6.5, height=4) 

enter image description here

+0

非常感谢你。我怀疑我需要使用融化,但我不知道我需要这样做两个变量作为id。再次感谢。 – 2013-04-16 10:23:55

+0

不客气。我很高兴能够提供帮助。 – bdemarest 2013-04-16 22:18:19