Adding legend to ggplot when lines were added manually

前端 未结 1 548
南旧
南旧 2020-12-05 18:31

I have a plot in ggplot with 4 separate lines that I have added with a separate geom_line() argument. I would like to add legend but scale_colour_manual doesn\'t work in thi

相关标签:
1条回答
  • 2020-12-05 18:47

    Just set the color name in aes to whatever the line's name on the legend should be.

    I don't have your data, but here's an example using iris a line with random y values:

    library(ggplot2)
    
    line.data <- data.frame(x=seq(0, 10, length.out=10), y=runif(10, 0, 10))
    
    qplot(Sepal.Length, Petal.Length, color=Species, data=iris) +
      geom_line(aes(x, y, color="My Line"), data=line.data)
    

    enter image description here

    The key thing to note is that you're creating an aesthetic mapping, but instead of mapping color to a column in a data frame, you're mapping it to a string you specify. ggplot will assign a color to that value, just as with values that come from a data frame. You could have produced the same plot as above by adding a Species column to the data frame:

    line.data$Species <- "My Line"
    qplot(Sepal.Length, Petal.Length, color=Species, data=iris) +
      geom_line(aes(x, y), data=line.data)
    

    Either way, if you don't like the color ggplot2 assigns, then you can specify your own using scale_color_manual:

    qplot(Sepal.Length, Petal.Length, color=Species, data=iris) +
      geom_line(aes(x, y, color="My Line"), data=line.data) +
      scale_color_manual(values=c("setosa"="blue4", "versicolor"="red4",
                                  "virginica"="purple4", "My Line"="gray"))
    

    enter image description here

    Another alternative is to just directly label the lines, or to make the purpose of the lines obvious from the context. Really, the best option depends on your specific circumstances.

    0 讨论(0)
提交回复
热议问题