在 R 中绘制条形图

问题描述 投票:0回答:1
# A tibble: 6 × 7
  No    Region     District `Name of School`  Male Female Total
  <chr> <fct>      <fct>    <chr>            <dbl>  <dbl> <dbl>
1 1     South East Gaborone Bokamoso CJSS      545    516  1061
2 2     South East Gaborone Marang CJSS        550    567  1117
3 3     South East Gaborone Nanogang CJSS      493    558  1051
4 4     South East Gaborone Maikano CJSS       440    388   828
5 5     South East Gaborone Motswedi CJSS      443    475   918
6 6     South East Gaborone Gaborone West      415    401   816

我想在我的数据中声明并添加一个新的分类变量性别。性别变量应取决于数据集中已提供的男性和女性的值。重点是绘制一个分组条形图,其中区域在 x 轴上分为性别类别

# A tibble: 6 × 7
  No    Region     District `Name of School`  Male Female Total
  <chr> <fct>      <fct>    <chr>            <dbl>  <dbl> <dbl>
1 1     South East Gaborone Bokamoso CJSS      545    516  1061
2 2     South East Gaborone Marang CJSS        550    567  1117
3 3     South East Gaborone Nanogang CJSS      493    558  1051
4 4     South East Gaborone Maikano CJSS       440    388   828
5 5     South East Gaborone Motswedi CJSS      443    475   918
6 6     South East Gaborone Gaborone West      415    401   816
r dataframe ggplot2 bar-chart mutate
1个回答
0
投票

你需要先学习

tidy
数据原理

library(tidyverse)

# Create the dataframe df
df <- tibble(
  No = c("1", "2", "3", "4", "5", "6"),
  Region = factor(rep("South East", 6)),
  District = factor(rep("Gaborone", 6)),
  `Name of School` = c("Bokamoso CJSS", "Marang CJSS", "Nanogang CJSS", "Maikano CJSS", "Motswedi CJSS", "Gaborone West"),
  Male = c(545, 550, 493, 440, 443, 415),
  Female = c(516, 567, 558, 388, 475, 401),
  Total = c(1061, 1117, 1051, 828, 918, 816)
)

df %>% 
  select(-Total) %>% 
  pivot_longer(c(Male, Female), names_to = "gender", values_to = "schools") %>% 
  ggplot(aes(`Name of School`, y = schools, fill = gender)) +
  geom_col(position = "dodge")

创建于 2024-03-07,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.