ss0208535 ss0208535 - 3 months ago 13
R Question

reversed legend using guide_legend()

I am an absolute beginner in

ggplot2
and practicing to use
guide_legend()
functions. I am not quite sure why
guide_legend()
reverses the order of the legend.

Here's the base example:

df <- data.frame(x = 1, y = 1:3, z = 1:3)
base <- ggplot(df, aes(x, y)) + geom_raster(aes(fill = z))


This nicely produces a raster graph.

However, when I add the following line, the order of legend gets reversed. Can someone please explain why this is happening?

base + scale_fill_continuous(guide = guide_legend())


I'd appreciate any thoughts. Is there anyway I can reverse the order?

Thanks




Addition: I want to add that
reverse = FALSE
by default for guide_legend. I think
reverse=TRUE
will fix it, but I am not understanding the point of resetting the default value. Is there anything wrong that I am doing?

Here's the guide: I am referring to http://docs.ggplot2.org/current/guide_legend.html

Here's the pic: enter image description here This pic is from above website.

Answer

Your base plot has a continuous color scale, which you can see in the legend:

base <- ggplot(df, aes(x, y)) + geom_raster(aes(fill = z))

enter image description here

This converts it to a discrete color scale, because setting guide="legend" or guide=guide_legend() creates a discrete scale (this is documented in the help):

base + scale_fill_continuous(guide = guide_legend())

enter image description here

For a continuous color scale, you could use the code below, but it's not necessary because that's already what ggplot does by default when the color variable is continuous (as shown in your base plot):

base + scale_fill_continuous(guide = guide_colourbar())

Keep discrete color scale, but reverse order so that highest value is on top. I've also set the breaks so that only 3 colors are displayed in the legend:

base + scale_fill_continuous(breaks=1:3, guide=guide_legend(reverse=TRUE))

enter image description here

UPDATE: To address the long comment thread, here are the three plots from the ggplot help for guide_legend. But note that the first one is not actually displayed on the ggplot help page; only the code is shown.

df <- reshape2::melt(outer(1:4, 1:4), varnames = c("X1", "X2"))

p1 = ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p2 = p1 + scale_fill_continuous(guide = "legend")
p3 = p1 + scale_fill_continuous(guide = guide_legend())

enter image description here

Comments