Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

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

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:

 library(ggplot2)
    df<-as.data.frame(cbind(rep(1:10,10),
                            rep(1:10,each=10),
                            rnorm(100)))

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

As you can see the V3 is the same for the color and the size of the data points. How can I merge the color gradient to the size scale (except do this manually in program such as Illustrator...)? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the guides() function of ggplot2. In this case:

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

ggplot2 will try to integrate the scales for you. It doesn't in this case because the default guide for a color scale is a colorbar and the default guide for size is a normal legend. Once you set them both to be legends, ggplot 2 takes over and combines them.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...