0

I have problems with ggplot in R.

Here is my code:

ggplot(plot3)+
  geom_line(mapping = aes(x= tider , y = andel_nätverk, color = "blue"))+
  geom_line(mapping = aes(x= tider, y= andel_fängelse, color = "green"))+
  geom_line(mapping = aes(x=tider, y= andel_reb, color = "red"))+
  labs(x = "Tid", y= "Andel", color = "Platser")+
  scale_color_manual(labels = c("R", "F", "N"), values = c("red", "green", "blue"))

The problem is that "andel_nätverk" and "andel_reb" changes place on the colors in the plot. So "andel_nätverk" is red and "andel_reb" is blue. If I put the color-argument outside aes the colors fit correctly but then I can't use scale_color_manuel and get legends. Does anyone know what the problem is ?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). This increases the chance that someone can help you. – ziggystar Apr 23 '21 at 09:19
  • Make use of named vectors: `labels = c(red = "R", green = "F", blue = "N"), values = c(red = "red", green = "green", blue = "blue")`. – stefan Apr 23 '21 at 10:28

1 Answers1

0

What you put inside aes() will be the name of the line on the legend. Color is supplied by scale_color_manual. Here you try to define color in geom_line as well, which is only where the mapping is applied (but not colored). Without a reprex, I cannot confirm this will work, but this should work below. Note the use of a named vector inside scale_color_manual() that forces the association of color.

ggplot(plot3)+
  geom_line(mapping = aes(x= tider , y = andel_nätverk, color = "blue line"))+
  geom_line(mapping = aes(x= tider, y= andel_fängelse, color = "green line"))+
  geom_line(mapping = aes(x=tider, y= andel_reb, color = "red line"))+
  labs(x = "Tid", y= "Andel", color = "Platser")+
  scale_color_manual(
    labels = c("R", "F", "N"),
    values = c("red line" = "red", "green line" = "green", "blue line" = "blue"))

BTW - your colors were switching positions because without a named vector being used in values the order is applied based on the order of items in the legend (usually alphabetical if you don't use a factor).

chemdork123
  • 12,369
  • 2
  • 16
  • 32