【问题标题】:adding legend to a bar plot (R ggplot)将图例添加到条形图(R ggplot)
【发布时间】:2021-03-31 14:20:02
【问题描述】:

我试图在我的条形图中添加一个图例,但没有成功。 这就是我的数据的样子:三列,第一列是一个带有组名的因子,然后是两个数字,称为“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)) 

这完全符合我的要求,but how do I add a legend to this?

然后我尝试将我的数据转长:

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")

I don't want it separate like that

ggplot(data_long,aes(x = `age group`, y = `rate`, fill = `dose`)) +
  geom_col(position = position_stack(reverse = T))

but this comes out stacked, and I don't want it to be over 100%

有什么想法吗? 提前致谢!

【问题讨论】:

  • 请将您的数据作为对象包含在内:使用dput(data) 这将有助于其他人测试和验证解决方案。
  • 谢谢!我已经做了。我不熟悉 dput,这是一个有用的工具

标签: r ggplot2 bar-chart geom-bar geom-col


【解决方案1】:

这应该做你想做的:

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)) 

reprex package (v1.0.0) 于 2021 年 3 月 31 日创建

【讨论】:

  • 谢谢!我会详细了解position = position_dodge(width = 0, preserve = "total"),看来这就是解决方案所在
猜你喜欢
  • 2023-01-27
  • 1970-01-01
  • 2020-12-02
  • 2019-06-21
  • 2021-01-05
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 2021-05-21
相关资源
最近更新 更多