[英]Adding legend manually to R/ggplot2 plot without interfering with the plot
[英]adding legend to a bar plot (R ggplot)
我試圖在我的酒吧 plot 中添加一個圖例,但沒有成功。 這就是我的數據的樣子:三列,第一列是一個帶有組名的因子,然后是兩個數字,稱為“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))
有任何想法嗎? 提前致謝!
這應該做你想要的:
library(tidyr)
library(ggplot2)
data1 <-
data %>%
pivot_longer(-`age group`)
ggplot(data1)+
geom_col(aes(x=`age group`, y = value, fill = name), position = position_dodge(width = 0, preserve = "total"), width = 1.5, alpha = 0.5)+
scale_fill_manual(values = c("gray10", "skyblue"))+
labs(x = "Age",
y = "Percent",
fill = "Dose")+
ggtitle("Vaccination rate by age group \n Israel") +
theme_bw()+
theme(plot.title = element_text(hjust = 0.5))
由代表 package (v1.0.0) 於 2021 年 3 月 31 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.