【问题标题】:Creating a Grouped Bar Plot with Ggplot使用 Ggplot 创建分组条形图
【发布时间】:2019-04-16 22:38:39
【问题描述】:

我如何为分组条形图编码,其中我可以描绘每个菌株的 2 个值:一列代表铁饮食的细胞体积,另一列代表正常饮食的细胞体积?

我的 Excel 表格看起来像这样,它有多个列,但我想根据其中的 3 个列(应变、CV Iron、CV Normal)有选择地制作图表:

Strain      CV Iron        CV Normal
A             23              17
B             10              15
...

我希望我的分组条形图看起来像这样:

x 轴是“应变”,y 轴是“CV”,其中每个应变有 2 列:一列用于“CV Iron”,一列用于“CV Normal”,以及颜色编码列将基于饮食(CV Iron 或 CV Normal)。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我会举个例子:

    df1 <- data.frame(Strain = c("A","B","C","D"),
                  CVIron = c(12,15,16,21),
                  CVNormal = c(10,12,18,9))
    
    head(df1) 
      Strain CVIron CVNormal
        1      A     12       10
        2      B     15       12
        3      C     16       18
        4      D     21        9
    

    首先,您应该将两个 CV 列合并为一个。您可以在 reshape2 包中使用 melt 功能。

    library(reshape2)
    df2 <- melt(df1, id = "Strain")
    
    head(df2)
     Strain variable value
    1      A   CVIron    12
    2      B   CVIron    15
    3      C   CVIron    16
    4      D   CVIron    21
    5      A CVNormal    10
    6      B CVNormal    12
    7      C CVNormal    18
    8      D CVNormal     9
    

    然后您可以轻松应用 ggplot 函数。

    library(ggplot2)
    ggplot(data=df2, aes(x=variable, y=value, fill=Strain)) +
       geom_bar(stat="identity", position=position_dodge())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多