user3388408 user3388408 - 2 months ago 8
R Question

Using same alpha/size scale for 2 different plots with ggplot

I have 2 data frames I use to make 2 scatter plots. I use one column to set the alpha and size of the markers and I need the scaling in the second plot to be identical to the first. The problem is that while the values in plot A range from 0 to 1, in plot B they range from 0 to 0.5 (the scale in B should also be from 0 to 1)...

Quick example:

x=seq(from=1, to=10, by=1)
y=seq(from=1, to=10, by=1)
markerA=sample(0:100,10, replace=T)/100
markerB=sample(0:50,10, replace=T)/100
dfA=data.frame(x,y,markerA)
dfB=data.frame(x,y,markerB)
a<- ggplot(dfA,aes(x=x, y=y))
a <- a + geom_point(aes(alpha=dfA$markerA, size=dfA$markerA))
a
b<- ggplot(dfB,aes(x=x, y=y))
b <- b + geom_point(aes(alpha=dfB$markerB, size=dfB$markerB))
b


plot A
plot B

I think there should be an easy way to do this but I can't seem to find it...

bVa bVa
Answer

Just add scale_size and scale_alpha to your plots.
With ggplot2, remember to not use $variable in the aes

Here is an example:

enter image description here

a = ggplot(dfA,aes(x=x, y=y)) + 
geom_point(aes(alpha=markerA, size=markerA)) + 
scale_size(limits = c(0,1)) + 
scale_alpha(limits = c(0,1))

b = ggplot(dfB,aes(x=x, y=y)) + 
geom_point(aes(alpha=markerB, size=markerB)) + 
scale_size(limits = c(0,1)) + 
scale_alpha(limits = c(0,1))

grid.arrange(a,b)