How to combine scales for colour and size into one legend?

后端 未结 2 853
广开言路
广开言路 2020-12-01 21:39

I would like to know how to colorize the size_scale in scale_size() {ggplot2} in a plot where the size and color are from the same data.

Example:

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 21:43

    This can be achieved by requesting to use not a colourbar but a legend for the colour. Using your data frame:

      ggplot(df,aes(V1,V2))+
         geom_point(aes(colour=V3,size=V3))+
         scale_colour_gradient(low="grey", high="black",guide="legend")+
         scale_size(range=c(1,10))
    

    If you also want the colour bar, there is a little hack to achieve this that profits from the fact that you are not using the aesthetic fill. So you can map V3 to fill as well and it will draw a colourbar for this scale:

      ggplot(df,aes(V1,V2))+
         geom_point(aes(colour=V3,size=V3,fill=V3))+
         scale_colour_gradient(low="grey", high="black",guide="legend")+
         scale_size(range=c(1,10)) + 
         scale_fill_gradient(low="grey",high="black") +
         guides(fill=guide_colourbar(reverse=TRUE))
    

    I added the call to guides in order to have the colours in the colourbar ordered the same way as in the legend for the sizes.

提交回复
热议问题