Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot XY scatter - how to change alpha transparency for select points?

I have ~14,000 XY pairs to plot, and using ggplot2 for this.

Due to high numbers of points, I have had to use very low alpha=0.025. I want to highlight 7 XY points in a different color and more opaque, and have an accompanying text legend.

Currently, my colors for the 7 special data points do not show up because they are also at alpha=0.025. How do I increase the opaqueness for just these points?

Syntax I have so far is:

trial <- ggplot(df, aes(x = df$SeqIdentityMean, 
                        y = df$SeqIdentityStdDev,
                        color = factor(df$PfamA_ID))) + 
            geom_point(alpha=0.025) + 
            labs(title="Mean Vs. standard deviation of PfamA seed lengths", 
                 x="Average Length (aa)",
                 y="Standard  Deviation of Length (aa)") + 
            theme(legend.title=element_blank(),
                  legend.key=element_rect(fill='NA'))
like image 212
AksR Avatar asked Dec 19 '25 04:12

AksR


1 Answers

Just create an alpha column in your dataset, and set the points you want to stand out to alpha = 1:

library(ggplot2)
alpha_vector = rep(0.025, nrow(mtcars))
alpha_vector[c(3,6,8)] = 1
mtcars$alpha = alpha_vector
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(aes(alpha = alpha))

enter image description here

The trick here is to realize that alpha is just another aesthetic.

In addition, I would not plot 14k points directly and rely on alpha, I would just use 2d binning. For example using hexbin:

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_hexbin()
like image 94
Paul Hiemstra Avatar answered Dec 20 '25 21:12

Paul Hiemstra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!