首页 > 解决方案 > r中每个类别的条形图平均值

问题描述

此处是 R 新手,但无法找到这个可能简单问题的答案。我这里有一些数据:

数据图像

我只想绘制民主党人、共和党人和独立人士的平均信任水平,如下所示:

拟建地块

...使用ggplot。

我尝试了以下代码(Q4 = 政党从属列)...

hypothesis_1 <- ggplot(data = data.df, aes(x = Q4, y = avgTRUST))
graph_4 <- hypothesis_1 + geom_col(stat = 'identity', fill = "blue") + ggtitle("Trust in Government Institutions (by Political Party)") + theme_minimal() + theme(axis.title.x=element_blank()) + labs(y = "Trust Levels") + scale_y_continuous(breaks = seq(0,30,1)) 

...但它给了我一个我认为是“总计数”的 y 轴。数数

标签: rggplot2bar-chartaverage

解决方案


这可以工作,但在缺乏可重复数据的情况下无法测试:

library(tidyverse)
#Code
data.df %>%
  group_by(Q4) %>%
  summarise(avgTRUST=mean(avgTRUST,na.rm = T)) %>%
  ggplot(aes(x = Q4, y = avgTRUST))+
  geom_col(stat = 'identity', fill = "blue") +
  ggtitle("Trust in Government Institutions (by Political Party)") +
  theme_minimal() +
  theme(axis.title.x=element_blank()) +
  labs(y = "Trust Levels")

推荐阅读