如何在 geom_bar() 中使用多个位置参数
How to use multiple position arguments with 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))
我有以下数据框:
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))