【问题标题】:qplot factor by condition按条件划分的 qplot 因子
【发布时间】:2012-11-07 22:25:40
【问题描述】:

使用这个数据框,df:

bat.condition bat.group      bat.money
1              safe          2825.882
2              safe          2931.875
1              glsa          6975.882
2              glsa          5407.500
1              studyabroad   3084.706
2              studyabroad   2253.750 
1              jcc           4134.706
2              jcc           5550.625
1              eagg          4578.824
2              eagg          5456.250

我想在 x 轴上绘制一个带有组的条形图,在 y 轴上绘制货币。此外,我希望将条形图按它们发生的条件分开/分解。到目前为止,我已经使用了以下代码,它几乎是理想的。我有按组分解的条形,我想按条件进一步分解它。

qplot(factor(bat.group), data = df, geom = "bar", fill = bat.group, 
      weight = bat.money, position = "dodge")

这会产生这里看到的图像。

【问题讨论】:

    标签: r bar-chart ggplot2


    【解决方案1】:

    您通常可以使用interaction 函数获取分组:

     qplot(interaction(bat.condition, bat.group), data = df, geom = "bar", fill = bat.group, 
          weight = bat.money, position = "dodge")
    

    【讨论】:

    • 这就是我要找的——我没有在文档中搜索“交互”这个词。有道理。
    【解决方案2】:

    您可以将新变量添加到您的数据框并使用这样的构面:

    df$factor = factor(df$bat.group)
    qplot(as.character(bat.condition), data = df, geom = "bar", fill = bat.group, 
          weight = bat.money, position = "dodge", facets = . ~ factor)
    

    【讨论】:

      【解决方案3】:

      这是一个可以满足您要求的解决方案。我使用了ggplot 语法而不是qplot。我使用facet_wrap 通过bat.condition 分隔您的数据。此外,geom_barplot 需要参数 stat="identity" 否则它将尝试对您的数据进行 bin 处理。

      # Using ggplot2 version 0.9.2.1
      library(ggplot2)
      
      dat = read.table(header=TRUE, 
      text="bat.condition bat.group      bat.money
      1              safe          2825.882
      2              safe          2931.875
      1              glsa          6975.882
      2              glsa          5407.500
      1              studyabroad   3084.706
      2              studyabroad   2253.750 
      1              jcc           4134.706
      2              jcc           5550.625
      1              eagg          4578.824
      2              eagg          5456.250")
      
      
      p1 = ggplot(data=dat, aes(x=bat.group, y=bat.money, fill=bat.group)) +
           geom_bar(stat="identity") +
           facet_wrap(~ bat.condition)
      
      ggsave(plot=p1, filename="plot_1.png", height=5, width=8)
      

      编辑: 使用 fill=bat.condition 并添加 position="dodge" 将生成一个与您在评论中链接到的图形相似的图形。

      p2 = ggplot(data=dat, aes(x=bat.group, y=bat.money, fill=factor(bat.condition)))+
           geom_bar(position="dodge")
      
      ggsave(plot=p2, filename="plot_2.png", height=4, width=6)
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多