How to add legend in the ggplot

Hi
I'm trying to use R studio to draw line graph.
I have problems with adding a legend to a ggplot2 figure.
I try many solutions,but still come out the same figure.


library(ggplot2)
df <- data.frame(China,India,USA,World,Year)
colors <- c("China" = "blue", "India" = "red", "USA" = "green","World" = "dodgerblue1")
ggplot(df, aes(x=Year)) +
geom_line(aes(y = China),color="blue",size=1.5) +
geom_line(aes(y = India),color = "red",size=1.5)+
geom_line(aes(y = USA),color="green",size=1.5)+
geom_line(aes(y = World),color="dodgerblue1",size=1.5)+
ylim(0,10000000000)+
labs(x="Year",y="population",color="country")+
scale_color_manual(values = colors)

Hi,

ggplot is not very suited for plotting data in a wide-format data frame, you will save yourself a lot of grievance by using long-format data frames instead:

df <- data.frame(China,India,USA,World,Year) %>% gather(Country, Population, -Year)
ggplot(df, aes(x=Year, y=Population, Color=Country)) +
   geom_line(size=1.5) + ...

The legend comes for free. You can add your dressing (limits, color scheme etc) yourself.

Cheers
Steen

World <- c(7255653881,7340548192,7426103221,7510990456,7594270356)
China <- c(1364270000,1371220000,1378665000,1386395000,1392730000)
India <- c(1295604184,1310152403,1324509589,1338658835,1352617328 )
USA <- c(318386421,320742673,323071342,325147121,327167434)
Year <- c(2014,2015,2016,2017,2018)
df <- data.frame(China,India,USA,World,Year) %>% gather(Country, Population, -Year)
ggplot(df, aes(x=Year, y=Population, color=Country)) +
geom_line(size=1.5)

I had a small spelling error in the aes statement, color should be with a lowercase c, not uppercase :slight_smile:

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Thanks for your respond.
I use your codes ,but still come out the same figure.


I don't know where to code the legend.

World <- c(7255653881,7340548192,7426103221,7510990456,7594270356)
China <- c(1364270000,1371220000,1378665000,1386395000,1392730000)
India <- c(1295604184,1310152403,1324509589,1338658835,1352617328 )
USA <- c(318386421,320742673,323071342,325147121,327167434)
Year <- c(2014,2015,2016,2017,2018)
df <- data.frame(China,India,USA,World,Year) %>% gather(Country, Population, -Year)
ggplot(df, aes(x=Year, y=Population, Color=Country)) +
geom_line(size=1.5)

Is this right?

Thank you so much!!! Finally got the legend.

To elaborate a bit, as soon as you add some grouping to your ggplot (by using one of the grouping aestethics like group, color, fill, line, ...) you will automatically get a legend.

2 Likes