4

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.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Katrin Leinweber
  • 1,316
  • 13
  • 33
  • Welcome to SO! Can you please try to narrow down the code? Adding images will also be helpful. – tonytonov Dec 10 '14 at 13:22
  • 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 Dec 10 '14 at 14:26
  • possible duplicate of [ggplot2 custom legend shapes](http://stackoverflow.com/questions/13456765/ggplot2-custom-legend-shapes) – Henrik Dec 10 '14 at 15:02
  • See also http://stackoverflow.com/questions/12751159/ggplot2-making-changes-to-symbols-in-the-legend/12751397#12751397 – Henrik Dec 10 '14 at 15:03

1 Answers1

9

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

tonytonov
  • 25,060
  • 16
  • 82
  • 98