首页 > 解决方案 > 如何在 geom_bar() 中使用多个位置参数

问题描述

我有以下数据框:

year = rep(c(2019,2020), 2)
month = rep(c("June","July"), 2)
male = c(11,13,15,17)
female = c(12,14,16,18)

df <- data.frame(cbind(year, month, male, female))

  year month male female
1 2019  June   11     12
2 2020  July   13     14
3 2019  June   15     16
4 2020  July   17     18

我想在条形图中显示数据,以便我在年份列中使用“闪避”位置,并且每年 6 月和 7 月都有相邻的条形图,它们本身由两个堆叠的条形图组成对于两种性别。任何建议如何实现这一目标?

标签: rggplot2geom-bar

解决方案


你可以在这一年面对:

library(tidyr)
library(dplyr)
df %>%
  pivot_longer(c(male,female), names_to="Sex") %>%
  mutate(value=as.numeric(value), month=factor(month, levels=c("June","July"))) %>%
ggplot(aes(month, value, fill=Sex)) +
  geom_bar(stat="identity", position=position_stack()) +
  facet_grid(~year, switch="x") + theme_minimal()

在此处输入图像描述

如果您认为月份标签高于年份标签会更好看,您可以调整axis.text。

df %>%
  pivot_longer(c(male,female), names_to="Sex") %>%
  mutate(value=as.numeric(value),
         month=factor(month, levels=c("June","July")),
         Month=paste(year,month,sep="-")) %>%
ggplot(aes(month, value, fill=Sex)) +
  geom_bar(stat="identity", position=position_stack()) +
  theme_minimal() + xlab("") + 
  facet_grid(~year, switch='x') + 
  theme(axis.text.x = element_text(margin = margin(t = -1, unit = "cm")))

在此处输入图像描述


资料

df <- structure(list(year = c("2019", "2020", "2019", "2020"), month = c("June", 
"June", "July", "July"), male = c("11", "13", "15", "17"), female = c("12", 
"14", "16", "18")), class = "data.frame", row.names = c(NA, -4L))

推荐阅读