我试图在我的条形图中添加一个图例,但没有成功。这就是我的数据的样子:三列,第一列是一个带有组名的因子,然后是两个数字,称为“1st_dose”和“2nd_dose”(这些是该年龄段的疫苗接种率)。
我的数据:
structure(list(`age group` = structure(1:9, .Label = c("10-19",
"20-29", "30-39", "40-49", "50-59", "60-69", "70-79", "80-89",
"90+"), class = "factor"), `1st_dose` = c(20.9, 72.8, 77.4, 82.2,
87.1, 88.6, 97.2, 94.5, 97.3), `2nd_dose` = c(17.7, 62.8, 69.1,
75.4, 80.9, 84, 93.6, 90.6, 91.6)), row.names = c(NA, -9L), class = c("tbl_df",
"tbl", "data.frame"))
我制作的第一张图是使用以下代码:
ggplot(data)+geom_bar(aes(x=`age group`, y = `1st_dose`), stat = "identity")+
geom_bar(aes(x=`age group`, y = `2nd_dose`), stat = "identity", fill="skyblue", alpha = 0.5)+
ylab("percent")+ggtitle("Vaccination rate by age group \n Israel") +
theme_bw()+theme(plot.title = element_text(hjust = 0.5))
这完全符合我的要求,但是我该如何添加一个图例呢?
然后我试图把我的数据变长:
data_long <- data %>% pivot_longer(cols = c(`1st_dose`,`2nd_dose`), names_to = "dose",
values_to = "rate")
并尝试了两种具有图例的图表变体,但看起来也不像我想要的那样:
ggplot(data_long,aes(x = `age group`, y = `rate`, fill = `dose`)) +
geom_col(position = "dodge")
ggplot(data_long,aes(x = `age group`, y = `rate`, fill = `dose`)) +
geom_col(position = position_stack(reverse = T))
有任何想法吗?提前致谢!