Assign color to lines ggplot2

JuliaK picture JuliaK · Jan 8, 2016 · Viewed 10.6k times · Source

I would like to do a line plot with 5 different line using ggplot2. I used the following code.

plot <- ggplot() + 
  geom_line(data=MS, aes(x=date, y=MSCI.World.PI, color='MS')) +
  geom_line(data=S, aes(x=date, y=SandP.TR, color='S')) +
  geom_line(data=BR, aes(x=date, y=MSCI.BRIC.PI, color='BR')) +
  geom_line(data=HF, aes(x=date, y=HFRX, color='HF')) +
  geom_line(data=LP, aes(x=date, y=LPX50.TR, color='LP')) +
  scale_color_manual(values = c("red", "blue", "green", "yellow", "violet" )) +
  labs(color="Indices") +
  xlab('Time') +
  ylab('Price')
plot

The result is the following plot: Corresponding Plot

The "wrong" part is, that the colors did not get sorted as was intended, meaning the first line ("MS") is not assigned to the first color ("red"). It seems like the line get assigned to the colors alphabetically.

Is there any way that I can change the assignment in such way that the first line is assingned to the first color ins the scale_color_manuel statement, the second line to the second color and so forth?

Answer

Spacedman picture Spacedman · Jan 8, 2016

Specifying the colours as a named vector does the trick, and makes the mapping explicit:

scale_color_manual(
      values = c(
           MS="red",
           S="blue",
          BR="green",
          HF="yellow",
          LP="violet" ))