How to set multiple legends for the same aesthetic in ggplot2?

前端 未结 1 1116
闹比i
闹比i 2020-12-19 06:00

I am plotting data from multiple dataframes in ggplot2 as follows:

# subset of iris data
vdf = iris[which(iris$Species == \"virginica\"),]
# plot from iris a         


        
相关标签:
1条回答
  • 2020-12-19 06:42

    You should set the color as an aes to show it in the legend.

    # subset of iris data
    vdf = iris[which(iris$Species == "virginica"),]
    # plot from iris and from vdf
    library(ggplot2)
    ggplot(iris) + geom_line(aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) +
      geom_line(aes(x=Sepal.Width, y=Sepal.Length, colour="gray"), 
                size=2, data=vdf)
    

    enter image description here

    EDIT I don't think you can't have a multiple legends for the same aes. here aworkaround :

    library(ggplot2)
    ggplot(iris) + 
      geom_line(aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) +
      geom_line(aes(x=Sepal.Width, y=Sepal.Length,size=2), colour="gray",  data=vdf) +
       guides(size = guide_legend(title='vdf color'))
    

    enter image description here

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