Add legend to ggplot2 line plot

前端 未结 3 1979
长发绾君心
长发绾君心 2020-11-21 11:44

I have a question about legends in ggplot2. I managed to plot three lines in the same graph and want to add a legend with the three colors used. This is the code used

<
3条回答
  •  情书的邮戳
    2020-11-21 12:23

    I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:

    ##Subset the necessary columns
    dd_sub = datos[,c(20, 2,3,5)]
    ##Then rearrange your data frame
    library(reshape2)
    dd = melt(dd_sub, id=c("fecha"))
    

    All that's left is a simple ggplot command:

    ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
      scale_colour_manual(values=c("red","green","blue"))
    

    Example plot

    enter image description here

提交回复
热议问题