在ggplot2中的geom_bar上堆叠多个列

Far*_*ani 1 r 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. 最后,我想通过根据物种对它们进行分组来对颜色进行着色(即,在Excel图表的x轴标签上指示的物种E&C)

我使用的数据类似于:

  • pop 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

bde*_*est 5

这是一个可以满足您的需求的解决方案.但请注意,ggplot的设计不允许在单个图中单独使用"阴影"和"颜色"参数.相反,我使用灰色填充颜色对您obs和proc类别进行着色,并且我将物种分组为小平面(而不是以不同方式对它们进行着色).

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述