How to fill the fields in the geom_point legend with color with dots, and not just increase their size?

I have a similar problem described here under "2- After two legends ..." but instead of increasing the point size (which eventually expands the legend as well), I would like to fill each box in the legend with the appropriate color. As in the legend of the bar plot. Sample data and code here .

After looking at a few other questions here, the ggplot doc, etc., I've tried variations of the code snippets I found but couldn't find a solution. Point symbols have always been preserved in the legend.

Therefore: If possible, how to tweak or replace the dot / scatter / bubble legend so that it looks like a line plot legend? Or, more generally, how to replace the legend of a given geomet in ggplot2 with another? Thanks 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 have collected from other SO answers ...

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

      

... keeps dots instead of expanding the color to fill the legend box, regardless of the arguments and data sources I'm trying to use for the guides () and list ().

On the other hand:

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

      

... draws beautifully colored boxes to the legend. This is what I am trying to do for the bubble plot.

+3


source to share


1 answer


You won't be able to get the type legend fill

as such, 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

+3


source







All Articles