leo
leo

Reputation: 3749

qplot alpha value as a vector

I want to set the alpha value of a point in a qplot with a vector (based on the plotted values).

library(ggplot2)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
alpha = rep(.8,nrow(dsamp)); alpha[dsamp$clarity=="I1"] <- 1
qplot(carat, price, data=dsamp, colour=clarity,size=I(4),alpha=alpha)

When I execute the code as above, there no difference when I create the alpha vector like this:

alpha = rep(.1,nrow(dsamp)); alpha[dsamp$clarity=="I1"] <- 1

I want for the points with dsamp$clarity!="I1" to have some less transparency as with both of the codes above. How can I achieve this?

Upvotes: 2

Views: 558

Answers (1)

alexwhan
alexwhan

Reputation: 16026

I would use ggplot() and map alpha to clarity. You can then manually set what value of alpha you need for each levels of the factor.

levels(dsamp$clarity)
[1] "I1"   "SI2"  "SI1"  "VS2"  "VS1"  "VVS2" "VVS1" "IF"
alpha <- c(1, rep(0.25, times=(length(levels(dsamp$clarity))-1)))
names(alpha) <- levels(dsamp$clarity)
alpha
  I1  SI2  SI1  VS2  VS1 VVS2 VVS1   IF 
 0.5  1.0  1.0  1.0  1.0  1.0  1.0  1.0

You can then:

ggplot(dsamp, aes(carat, price)) + geom_point(aes(alpha=clarity, colour=clarity), size=I(4)) +
  scale_alpha_manual(values=alpha)

Which as far as I can tell, gives you what you want. You can obviously set a different levels for I1 when you create alpha.

Upvotes: 2

Related Questions