How to set different "size" in one ggplot() object

241 views
Skip to first unread message

Ming Little

unread,
Nov 26, 2022, 11:48:57 AM11/26/22
to ggplot2
Hi,
I want to draw a plot with both geom_point() and geon_segment(), and I need to adjust the size of the points or the lines in the plot. It is easy to do this with scale_size(range= c(0,any value)).

An example plot code:
ggplot(data = data.frame(a=1:3,b=2:4,s=3:5,c=as.character(4:6)))+
  geom_segment(mapping = aes(x=a,xend=b,y=b,yend=a,size=s))+
  geom_point(mapping = aes(x=a,y=b,size=s,color=c))+
  scale_size(range(0,5))

But if i want to set different range to points and lines, i found i can't do that because a ggplot() can have only one scale. I cant set a range of c(0,5) to points and set a different range of c(0,2) to the lines. 
I usually the same problem encounter the same problem when i want to set more than one scale of color to different layers in one plot.

I have solved the problem by modifing the GeomPoint and geom_point(), set a new aes name like point_size to make it separate from the normal size aes. 

 But i don't think all the ggplot2 users can do this and maybe there is any "normal way" or "offical way" to set different size in one ggplot() without modifing the original code?

wouter...@hotmail.com

unread,
Dec 16, 2022, 1:39:11 PM12/16/22
to ggplot2
There's no "normal way" using just ggplot2. But there are extension packages, like ggnewscale (https://github.com/eliocamp/ggnewscale) or relayer (https://github.com/clauswilke/relayer). These make it a lot easier than having to modify the geoms.

Something like:

library(ggnewscale)
ggplot(data = data.frame(a=1:3,b=2:4,s=3:5,c=as.character(4:6)))+
  geom_segment(mapping = aes(x=a,xend=b,y=b,yend=a,size=s))+
  scale_size(range = c(0, 2)) +
  new_scale('size') +
  geom_point(mapping = aes(x=a,y=b,size=s,color=c))+
  scale_size(range = c(0,5))

Do note that in your example, this isn't necessary, since the size of lines should now be mapped to linewidth, not size:

ggplot(data = data.frame(a=1:3,b=2:4,s=3:5,c=as.character(4:6)))+
    geom_segment(mapping = aes(x=a,xend=b,y=b,yend=a,linewidth=s))+
    geom_point(mapping = aes(x=a,y=b,size=s,color=c))+
    scale_linewidth(range = c(0, 2)) +
    scale_size(range = c(0, 5))
Reply all
Reply to author
Forward
0 new messages