`fill` scale is not shown in the legend

2020-06-12 05:32发布

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?

sample plot

标签: r ggplot2
4条回答
我想做一个坏孩纸
2楼-- · 2020-06-12 05:52

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

Ggplot fill-color-shape

查看更多
对你真心纯属浪费
3楼-- · 2020-06-12 06:01

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

查看更多
做个烂人
4楼-- · 2020-06-12 06:03

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.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-06-12 06:03

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)

enter image description here

查看更多
登录 后发表回答