【问题标题】:ggplot2 bar plot by two groups and mean of y variableggplot2条形图由两组和y变量的平均值
【发布时间】:2018-07-21 11:30:15
【问题描述】:

我正在尝试创建一个条形图,其中我有两组,y 变量是其中一组的平均值。

Sample Bar Graph

所以看看上面照片中的条形图,我有按国家和亲社会分组的条形图,在 y 轴上我取了亲社会个体的比例。但是,我只能创建一个仅取亲社会平均值并按国家/地区分组的条形图。基本上,每个县只有一个酒吧。这不正是我正在寻找的。到目前为止,这是我用来对条形图的数据进行分组的代码,但有点不成功。

plotData <- myData2[!is.na(myData2$prosocial),]
plotData <- plotData %>% 
  mutate(mean_prosocial = mean(prosocial)) %>% 
  group_by(country) %>%
  summarise(mean_prosocial = mean(prosocial),se = sd(prosocial) / sqrt(n()))

这仅按国家/地区分组,如果我也想按亲社会分组,我显然只是得到平均变量的 NA。以下是工作数据的链接: workable data.

谢谢。

【问题讨论】:

    标签: r ggplot2 grouping bar-chart


    【解决方案1】:

    假设您想找出各个国家/地区的亲社会/非亲社会比例:

    require(dplyr)
    require(ggplot2)
    

    首先找出每个国家/地区有多少观测值。后面会用到分数计算。

    count_country <- myData2 %>% 
            filter(!is.na(prosocial)) %>% 
            group_by(country) %>% 
            summarise(n = length(country)) %>% 
            ungroup
    

    接下来找出各国的亲社会/非亲社会计数。

    count_prosocial <- myData2 %>% 
            filter(!is.na(prosocial)) %>% 
            group_by(country, prosocial) %>% 
            summarise(n = length(prosocial)) %>% 
            mutate(prosocial = as.factor(prosocial))
    

    按国家/地区名称合并两个数据框并找到分数:

    df <- count_prosocial %>% 
            left_join(count_country, by = "country") %>% 
            mutate(frac = round(n.x / n.y, 2))
    

    使用 facet_wrap 显示不同国家/地区的分数:

    ggplot(data=df, aes(x=prosocial, y=frac, fill=prosocial)) +
      geom_bar(stat = "identity")+
      geom_text(aes(x=prosocial, y=frac, label = frac),
                position = position_dodge(width = 1),
                vjust = 2, size = 3, color = "white", fontface = "bold")+
      facet_wrap(~country)+
      labs(y =  "Fraction of prosocial/non-prosocial") +
      scale_fill_discrete(labels=c("Prosocial", "Individualist"))+
      theme(axis.title.x=element_blank(),
            axis.text.x=element_blank(),
            axis.ticks.x=element_blank())
    

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 2018-09-15
      • 2021-05-02
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2023-01-26
      • 2018-11-25
      • 2020-12-20
      相关资源
      最近更新 更多