Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill boxes in geom_point legend with color of points, not just increasing their size?

Tags:

r

ggplot2

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.

like image 760
Katrin Leinweber Avatar asked Jan 10 '23 07:01

Katrin Leinweber


1 Answers

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

like image 109
tonytonov Avatar answered Jan 12 '23 07:01

tonytonov