Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

alpha in geom_raster() overrides na.value = "transparent" in scale_fill_continuous() #4630

Closed
dholstius opened this issue Sep 28, 2021 · 1 comment

Comments

@dholstius
Copy link

dholstius commented Sep 28, 2021

Description

I'm trying to produce figures with geom_raster() that have:

  • 0% opacity for NA values; and
  • 50% opacity for finite values; with
  • fill colors for (continuous) finite values varying by value.

I thought that the code below would achieve that, but supplying alpha = I(0.5) in geom_raster(...) seems to override the intent of supplying na.value = "transparent" in scale_fill_continuous(...).

My expectation is that "50% opaque 'transparent'" should be identical to "transparent", not to "50% opaque white".

Reprex

library(tidyverse)

# use `faithfuld` but substitute `NA` for values less than 0.01
df <- mutate(faithfuld, density = if_else(density < 0.01, NA_real_, density))
p <- ggplot(df, aes(waiting, eruptions)) 

# - as expected: all NAs are 0% opacity
p + geom_raster(aes(fill = density)) + scale_fill_continuous(na.value = "transparent")

# - as expected: finite values are 50% opacity
# - not as expected: NAs are 50% (?) white rather than fully transparent
p + geom_raster(aes(fill = density), alpha = I(0.5)) + scale_fill_continuous(na.value = "transparent")
@thomasp85
Copy link
Member

I can see why this can appear baffling. The reason is that you are setting the transparency, not applying it. "transparent" is simply white with an alpha of zero. When you set the alpha of this to 0.5 it becomes semi-transparent white.

You can get what you want by using stage() to modify the calculated colours:

library(tidyverse)

df <- mutate(faithfuld, density = if_else(density < 0.01, NA_real_, density))
ggplot(df, aes(waiting, eruptions))  + 
  geom_raster(
    aes(fill = stage(
      start = density, 
      after_scale = farver::multiply_channel(fill, 'alpha', 0.5)
    ))
  ) + 
  scale_fill_continuous(na.value = "transparent")

Created on 2021-10-28 by the reprex package (v2.0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants