Add legend to geom_line() graph in r

后端 未结 3 1708
忘了有多久
忘了有多久 2020-12-28 15:04

I\'ve been trying to add legend to my ggplot, but failed miserably. I tried the function scale_colour_manual(), but the legend doesn\'t show up.



        
3条回答
  •  情话喂你
    2020-12-28 15:15

    To provide a more compact answer which only uses a single geom call:

    ggplot2 really likes long data (key-value pairs) better than wide (many columns). This requires you to transform your data prior to plotting it using a package like tidyr or reshape2. This way you can have a variable denoting color, inside your aes call, which will produce the legend.

    For your data:

    library(tidyr)
    library(ggplot2)
    
    plot_data <- gather(data, variable, value, -x)
    
    ggplot(plot_data, aes(x = x, y = value, color = variable)) +
      geom_line() +
      scale_color_manual(values = c("firebrick", "dodgerblue")) 
    

    You can then customize the legend via scale_color series of helpers.

提交回复
热议问题