user3388408
user3388408

Reputation: 131

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...

Upvotes: 1

Views: 2325

Answers (2)

hrbrmstr
hrbrmstr

Reputation: 78792

First, you shouldn't use $ inside ggplot2. Second, this may be a better overall approach:

library(dplyr)
library(tidyr)

bind_cols(dfA, select(dfB, markerB)) %>% 
  gather(marker, value, -x, -y) %>% 
  mutate(marker=gsub("marker", "", marker)) -> both

gg <- ggplot(both, aes(x, y)) 
gg <- gg + geom_point(aes(alpha=value, size=value))
gg <- gg + facet_wrap(~marker, ncol=1)
gg <- gg + scale_alpha_continuous(limits=c(0,1))
gg <- gg + scale_size_continuous(limits=c(0,1))
gg <- gg + theme_bw()
gg

enter image description here

There are color-blind friendly background or foreground colors you can use to make the alpha stand out more (neither alpha gray-on-gray nor alpha-gray on white is very friendly).

Upvotes: 1

bVa
bVa

Reputation: 3938

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)

Upvotes: 5

Related Questions