Ben
Ben

Reputation: 103

How to have separate legends for size and fill in ggplot

When I use a code similar to this, I get two separate legends for fill and size. However, I don't want the fill legend to show the points and the size legend to show the background.

ggplot(data=Temp1) +
geom_bar(mapping=aes(x=K,y=ImpactX,group=Area,fill=Area,size=ImpactX),show.legend=T,
stat='identity',position=position_dodge(0.8)) +
geom_point(mapping=aes(x=K,y=ImpactX,group=Area,size=ImpactX),
color='black',fill='transparent',shape=19,
position=position_dodge(0.8),show.legend=T,na.rm=T) +
scale_size_continuous(name='Size',range=c(1,4))

Here is my sample data (LINK). Just contains a data.table, Temp1.

enter image description here

Upvotes: 3

Views: 72

Answers (1)

Henry Cyranka
Henry Cyranka

Reputation: 3060

I used a combination of theme and some guide_legend with override.aes.

ggplot(data=Temp1) +
    geom_bar(mapping=aes(x=K,y=ImpactX,group=Area,fill=Area,size=ImpactX),show.legend=T,
             stat='identity',position=position_dodge(0.8)) +
    geom_point(mapping=aes(x=K,y=ImpactX,group=Area,size=ImpactX),
               color='black',fill='transparent',shape=19,
               position=position_dodge(0.8),show.legend=T,na.rm=T) +
    scale_size_continuous(name='Size',range=c(1,4)) + 
    theme(legend.key = element_rect(fill = "white",linetype = 0)) +
    guides(size = guide_legend(override.aes =list(fill = "white"))) + 
    guides(fill = guide_legend(override.aes = list(shape = NA)))

enter image description here

Upvotes: 3

Related Questions