问题
Is it possible to specify thresholds for color-scales?
Look at this example:
xy <- expand.grid(x=1:20,y=1:20)
xyd <- data.frame(xy,z=runif(400),a=rowSums(xy)/40)
g <- ggplot(xyd, aes(x=x, y=y, fill=z, alpha=a)) +
geom_tile() +
scale_alpha(range=c(0,1), limits=c(0.5,1))
g

What I want is that Values of a below 0.5 get an alpha value of 0 so that the lower left half will be invisible. Obviously I could transform the original data but that would destroy the legend.
回答1:
The threshold is working and the values outside that threshold are set to NA
; the problem is that an alpha
of NA
is getting rendered as full opacity. Setting the na.value
on the scale to 0
gets the results you want.
ggplot(xyd, aes(x=x, y=y, fill=z, alpha=a)) +
geom_tile() +
scale_alpha(range=c(0,1), limits=c(0.5,1), na.value = 0)

回答2:
None of my attempts to use the scales to control alpha were completely successful. My best attempt was to use ifelse
to control the value of a:
ggplot(xyd, aes(x=x, y=y, fill=z)) +
geom_tile(aes(alpha=ifelse(a<=0.5, 0, a))) +
scale_alpha(range=c(0,1))

So, a different approach is required: remove the values that you don't want to plot from the data:
xyd <- with(xyd, xyd[a>0.5, ])
ggplot(xyd, aes(x=x, y=y, fill=z)) +
geom_tile(aes(alpha=a))

来源:https://stackoverflow.com/questions/11950544/ggplot2-thresholds-for-scale-alpha