The "fill" scale is not shown in the legend

Here is my dummy code:

set.seed(1) df <- data.frame(xx=sample(10,6), yy=sample(10,6), type2=c('a','b','a','a','b','b'), type3=c('A','C','B','A','B','C') ) ggplot(data=df, mapping = aes(x=xx, y=yy)) + geom_point(aes(shape=type3, fill=type2), size=5) + scale_shape_manual(values=c(24,25,21)) + scale_fill_manual(values=c('green', 'red')) 

The resulting plot has a legend, but the 'type2' section does not reflect the scale of the fill value - is this design?

sample plot

+3
source share
4 answers

I know this is an old thread, but I ran into this exact problem and want to post it here for others like me. Although the accepted answer works, a less risky, cleaner method:

 library(ggplot2) ggplot(data=df, mapping = aes(x=xx, y=yy)) + geom_point(aes(shape=type3, fill=type2), size=5) + scale_shape_manual(values=c(24,25,21)) + scale_fill_manual(values=c(a='green',b='red'))+ guides(fill=guide_legend(override.aes=list(shape=21))) 

The key is to change the form in the legend to one that may have a “fill”.

+2
source

Another workaround is used here.

 library(ggplot2) ggplot(data=df, mapping = aes(x=xx, y=yy)) + geom_point(aes(shape=type3, fill=type2), size=5) + scale_shape_manual(values=c(24,25,21)) + scale_fill_manual(values=c(a='green',b='red'))+ guides(fill=guide_legend(override.aes=list(colour=c(a="green",b="red")))) 

Using guide_legend(...) with override_aes is a way to influence the look of the guide (legend). The hack is that here we "redefine" the fill colors in the manual with the colors that they should have in the first place.

+4
source

I played with data and came up with this idea. I first assigned the form in the first geom_point . Then I made the shapes empty. Thus, the contours remained in black. Thirdly, I manually assigned a specific form. Finally, I filled in the characters.

 ggplot(data=df, aes(x=xx, y=yy)) + geom_point(aes(shape = type3), size = 5.1) + # Plot with three types of shape first scale_shape(solid = FALSE) + # Make the shapes empty scale_shape_manual(values=c(24,25,21)) + # Assign specific types of shape geom_point(aes(color = type2, fill = type2, shape = type3), size = 4.5) 

enter image description here

+2
source

I'm not sure what you want looks like this?

 ggplot(df,aes(x=xx,y=yy))+ geom_point(aes(shape=type3,color=type2,fill=type2),size=5)+ scale_shape_manual(values=c(24,25,21)) 

Ggplot fill-color-shape

0
source

Source: https://habr.com/ru/post/1214031/


All Articles