【问题标题】:Grouped Barplot of Summarized Means with Ggplot2使用 Ggplot2 汇总均值的分组条形图
【发布时间】:2020-12-20 20:41:42
【问题描述】:

我觉得我遗漏了一些非常基本的东西,但我们很感激任何建议。

我有一个包含 19 个变量的大型数据集,包括分类变量和数值变量。我想生成一个图,其中三个变量(因为它们共享一个单位)按因子平均和排列。假样本数据:

Sex    Low Freq      High Freq      Bandwidth
M       3000         4011           1011
M       3000         3600           600 
M       2790         4237           1447
F       2700         3300           500
F       2900         4517           617
F       2813         3857           1044

我试过了:

ggplot(TripleSongAverages, aes(x=factor(Sex), y='Low Freq', 'High Freq', 'Bandwidth')) + stat_summary(fun.y="mean", geom="bar") 

但这只会产生带有第一个变量的图。

【问题讨论】:

    标签: r ggplot2 bar-chart grouped-table


    【解决方案1】:

    我建议使用tidyverse 方法来重塑数据并计算平均值。代码如下:

    library(tidyverse)
    #Data
    df <- structure(list(Sex = c("M", "M", "M", "F", "F", "F"), Low.Freq = c(3000, 
    3000, 2790, 2700, 2900, 2813), High.Freq = c(4011, 3600, 4237, 
    3300, 4517, 3857), Bandwidth = c(1011, 600, 1447, 500, 617, 1044
    )), class = "data.frame", row.names = c(NA, -6L))
    

    代码:

    #Reshape data and plot
    df %>% pivot_longer(cols = -Sex) %>%
      group_by(Sex,name) %>%
      summarise(Mean=mean(value,na.rm=T)) %>%
      #Plot
      ggplot(aes(x=factor(Sex), y=Mean,fill=name)) +
      geom_bar(stat='identity',position = position_dodge(0.9)) 
    

    输出:

    【讨论】:

    • 感谢您的帮助!出于某种原因,我的 df 只包括前 6 行(我有 41 行)。我收到以下错误:错误:无法对不存在的列进行子集化。 x 列FFFFF 等不存在。
    • 警告消息:在 format.data.frame(if (omit) x[seq_len(n0), , drop = FALSE] else x, : 损坏的数据帧:列将被截断或用 NA 填充
    • @michellemoyah 代替 df,使用所有数据,这里只有六行,因为它是一个示例。请注意您选择的列。
    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 2020-05-02
    • 1970-01-01
    • 2016-07-11
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多