首页 > 解决方案 > R中分组数据的条形图

问题描述

我想为 R 中的分组数据创建条形图,但找不到正确的代码。就我而言,我有三个不同的列,分别是数学分数、阅读分数和写作分数。同样对于所有这三列,我想将女性和男性的结果分开。查看我想要得到的结果的照片。在此处输入图像描述

数据在这里https://www.kaggle.com/spscientist/students-performance-in-exams 首先我需要找到女性数学、阅读和写作成绩的平均值和男性数学、阅读和写作的平均值结果,我使用这样的代码:

dta %>% 
  group_by(gender) %>%   
  summarise(mathmean = mean(math.score), 
            readingmean = mean(reading.score), 
            writingmean = mean(writing.score))

但是,我怎样才能制作如下图所示的条形图?

非常感谢 :)

标签: rbar-chart

解决方案


干得好:

# https://www.kaggle.com/spscientist/students-performance-in-exams
input_csv <- file.choose()

# read in the csv file
students_performance <- read_csv(input_csv)


students_performance %>% 
  select(gender, 'writing score', 'reading score', 'math score') %>% 
  group_by(gender) %>% 
  summarise_at(vars('writing score', 'reading score', 'math score'), funs(mean(., na.rm = TRUE))) %>% 
  pivot_longer(cols = c('writing score', 'reading score', 'math score'),
               names_to = 'type',
               values_to = 'score') %>% 
  ggplot(aes(x = factor(type, levels = c('writing score', 'reading score', 'math score')), y = score, fill = gender)) +
  geom_bar(stat = 'identity', position = 'dodge') +
  geom_text(aes(label = round(score, digits = 1)), position = position_dodge(width = 1), vjust = -0.2) +
  expand_limits(y = 80) +
  labs(
    title = "Student Performance by Gender",
    x = "Exam Type",
    y = "Mean Score",
    fill = "Gender"
  ) +
    theme(
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

在此处输入图像描述


推荐阅读