r - 如何在 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 月都有相邻的条形图,它们本身由两个堆叠的条形图组成对于两种性别。任何建议如何实现这一目标?
解决方案
你可以在这一年面对:
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))
推荐阅读
- r - 用 R 按一组间隔计算两列中的条目数
- r - 如何协调 purrr::map 与 case_when
- javascript - 当元素在视图中时,Slick-Carousel 自动播放开始
- python - 请解释此代码 list = ' '.join(i for i in list_text_from_file if not i in chars)
- vue.js - 基于项目类型的 Vuetify 格式单元格
- python - 硬编码逻辑回归评分代码
- python - 如何更改将 float('inf') 转换为 str 的 python 方式?
- reactjs - 胜利图,堆叠的条形一内一
- javascript - 将类传递给 Salesforce 中的组件
- excel - VBA Lotus DB Search - 获取当前文档的文件夹/视图名称