【问题标题】:Stacking multiple columns on a geom_bar in ggplot2在ggplot2中的geom_bar上堆叠多列
【发布时间】:2013-04-09 19:38:14
【问题描述】:

基本上:

  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. 最后,我想根据物种对条形图进行分组(即按物种 E 和 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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这里有一个解决方案,可以满足您的大部分需求。但请注意,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)
    

    【讨论】:

    • 非常感谢。我怀疑我需要使用melt,但我不知道我需要同时使用两个变量作为id。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2019-07-19
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多