Home > Back-end >  How to add a legend to a ggplot?
How to add a legend to a ggplot?

Time:07-15

I've been struggling with adding a legend to my ggplot2 plot in R. I've looked at many different answers on StackOverflow and elsewhere, but without luck. Could anyone tell me why the following code is not working? I've read that I needed to specify names and link them to the values in the legend, I've tried removing the scale_colour_manual and let it automatically generate a legend, but also without luck. This is my code:

country_data %>% ggplot(aes(x = Year))   
  geom_line(country_data_india, mapping=aes(y = as.numeric(TotPop1Jan), color = "India"),size=1.25, color="#339999")  
  geom_line(country_data_china, mapping=aes(y = as.numeric(TotPop1Jan), color = "China"),size=1.25, color="#993333")   theme_minimal()  
  labs(y="Total Population (in thousands)", title="Population of China and India from 1950 to 2021", subtitle="United Nations, Department of Economic and Social Affairs, Population Division (2022).\nWorld Population Prospects 2022, Online Edition.\n© Jeroen De Ryck")  
  theme(plot.subtitle = element_text(size = 8, colour ="darkgrey"), axis.line = element_line(colour = "black"), axis.ticks = element_line(linetype=1), axis.ticks.x = element_line())    
  scale_x_continuous(breaks = seq(1950,2021,5))  
  scale_y_continuous(breaks = seq(300000, 1500001, 200000))   
  scale_colour_manual("", breaks=c("India", "China"), values=c("India"="#339999", "China"="#993333"))

This is the result, without a legend as you can see.

Population of China and India from 1950 to 2021

CodePudding user response:

Add the parameter 'labels' to 'scale_color_manual' in order with the breaks:

scale_colour_manual("", breaks=c("India", "China"), values=c("India"="#339999", "China"="#993333"), labels=c("India", "China"))

To know more: https://ggplot2.tidyverse.org/reference/scale_manual.html

  • Related