如何在geom_bar()中使用多个位置参数
我有以下数据框:如何在geom_bar()中使用多个位置参数,r,ggplot2,geom-bar,R,Ggplot2,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
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
year=rep(c(20192020),2)
月份=代表(c(“六月”、“七月”),2)
男性=c(11,13,15,17)
女性=c(12,14,16,18)
df你可以在年份上分面:
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))
df我想你想要month=rep(c(“六月”、“七月”),每个=2)