user248237
user248237

Reputation:

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

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

# subset of iris data
vdf = iris[which(iris$Species == "virginica"),]
# plot from iris and from vdf
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)

the legend for colour includes only entries from iris, and not from vdf. how can I make ggplot2 add a legend from data=vdf, which in this case would be a gray line below the legend for iris? thanks.

Upvotes: 11

Views: 5235

Answers (2)

tjebo
tjebo

Reputation: 23737

There is currently no vanilla ggplot2 option to set two scales for the same aesthetic.

There are, as of today (July 2022), "only" three packages available to allow creation of more than one scale for the same aesthetic. These are

The ggnewscale package comes with three functions, new_scale_color, new_scale_fill, and new_scale for other aesthetics than color or fill.

library(ggplot2)
library(ggnewscale)

vdf <- iris[which(iris$Species == "virginica"), ]

ggplot(iris) +
  geom_line(aes(x = Sepal.Width, y = Sepal.Length, colour = Species)) +
  ## the guide orders are not a necessary part of the code 
  ## this is added for demonstrating purpose and because
  ## the OP wanted a grey line below the Species
  scale_color_discrete(guide = guide_legend(order = 1)) +
  ## add the new scale here
  new_scale_color() +
  ## then add a new color aesthetic, all else as per usual
  geom_line(
    data = vdf, aes(x = Sepal.Width, y = Sepal.Length, colour = "vdf"),
    size = 2
  ) +
  scale_color_manual(NULL, values = "grey", guide = guide_legend(order = 2))

Created on 2022-07-03 by the reprex package (v2.0.1)

Upvotes: 10

agstudy
agstudy

Reputation: 121568

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

Upvotes: 7

Related Questions