`fill` scale is not shown in the legend

2020-06-12 06:00发布

问题:

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'))

Resulting plot has a legend but it's 'type2' section doesn't reflect scale of fill value - is it by design?

回答1:

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

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 shape in the legend to one of those that can have a 'fill'.



回答2:

Here's a different workaround.

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 appearance of the guide (the legend). The hack is that here we are "overriding" the fill colors in the guide with the colors they should have had in the first place.



回答3:

I played with the data and came up with this idea. I first assigned shape in the first geom_point. Then, I made the shapes empty. In this way, outlines stayed in black colour. Third, I manually assigned specific shape. Finally, I filled in the symbols.

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)



回答4:

I'm not sure if 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))



标签: r ggplot2