Search code examples
rggplot2bar-chartgeom-bargeom-col

adding legend to a bar plot (R ggplot)


I am trying to add a legend to my bar plot, with no success. This is what my data looks like: three columns, first is a factor with a group name, and than two numeric called "1st_dose" and "2nd_dose" (those are rates of vaccinations among that age group).

my data:

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

first graph I made was with this code:

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

This came out exactly as I wanted, but how do I add a legend to this?

then I tried to turn my data long:

data_long <- data %>% pivot_longer(cols = c(`1st_dose`,`2nd_dose`), names_to = "dose",
                                   values_to = "rate") 

and tried two variations of graphs which have legends, but don't look the way I want them too:

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%

any ideas? Thanks in advance!


Solution

  • This should do what you want:

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

    Created on 2021-03-31 by the reprex package (v1.0.0)