5
votes

I'm having a similar problem as described in here under "2- After having the two legends...", but instead of increasing the point size (which eventually also enlarges the legend itself), I would like fill each box in the legend with the corresponding color. Like in a bar plot's legend. Data & code examples here.

Looking through several other questions here, the ggplot docu, etc., I tried variations of code-snippets I found, but couldn't figure out a solution. The legend always retained the point symbols.

Therefore: If possible, how to tweak or replace the legend of a point/scatter/bubble plot so that it looks like the legend of a bar plot? Or, more generally, how to replace the legend of a given geom in ggplot2 with that of a different one? Thank you for any hints!

Edit: Example with mtcars data

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(colour = factor(cyl), size = qsec))
p

Adding what I gathered from other SO-answers...

p <- p + guides(colour = guide_legend(override.aes = list(fill = unique(mtcars$cyl))))
p

...keeps the points, instead of expanding the color to fill the legend box, no matter arguments and datasources I try for guides() and list().

On the other hand:

ggplot(mtcars, aes(wt, mpg)) + geom_bar(aes(fill = factor(cyl)), stat="identity")

...draws nicely color-filled boxes to the legend. That's what I'm trying to do for a bubble plot.

1
Welcome to SO! Can you please try to narrow down the code? Adding images will also be helpful.tonytonov
Oh, I assumed code on GitHub with example csv. would be sufficient, sorry. Added minimal code above. I can't post pictures yet, but I hope the description in combination with the standard example data is clear.Katrin Leinweber
possible duplicate of ggplot2 custom legend shapesHenrik

1 Answers

9
votes

You won't be able to get a fill-type legend per se, but you can easily emulate it:

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point(aes(colour = factor(cyl), size = qsec)) + 
  guides(col = guide_legend(override.aes = list(shape = 15, size = 10)))

enter image description here