Home > other >  How to change color of lines depending on column value
How to change color of lines depending on column value

Time:11-20

I'm trying to make a graph using ggplot about the historic life expectancy of countries only from Europe and the Americas, from a dataframe. My idea was to make the lines from all European countries blue and the Americas red.

This is my code:

ggplot(AmericasEuropeData, aes(x = year, y = lifeExp, group = country, color = country))  
  geom_line(lwd = 1, show.legend = FALSE)   
  scale_color_manual(values = country_colors)  
  theme_bw()   theme(strip.text = element_text(size = rel(1.1)))  
  ggtitle("Americas   Europe")  
  geom_vline(xintercept=2020, linetype="dashed")  
  ylab("Life Expectancy")  
  xlab("Year")

which displays the following graph:

Combined graph

I tried changing color = country to color = continent but it turned all of the lines grey instead of a different color for each continent. How can I solve this ? I know I am probably messing up something really simple.

Preview of the AmericasEuropeData dataframe

dataframe

CodePudding user response:

It worked perfectly by changing color = country to color = continent and removing scale_color_manual(values = country_colors) as @AllanCameron said.

This is how it looks now:

final image

  • Related