Search code examples
rggplot2transparency

How to draw transparent lines in ggplot2


I want to hide elements in my ggplot2 facets depending on a given variable. My first idea was to just switch those elements transparent, but they do not completely disappear from the plot (see image below).

For a label value less than 1 I dont want to plot the segment and the text.

library(tidyverse)
library(ggplot2)

carData <- mtcars
# get the max for each gear facet
df2 <- carData %>% group_by(gear) %>%
  summarise(ypos = max(mpg)*1.1) %>%
  mutate(x = 1, xend = 2) # use your factor level locators
df2$trans <- c(0,0,1)
df2$label <- c(0.1,0.1,3)

carData$cyl <- factor(carData$cyl)

p <- ggplot(carData, aes(cyl, mpg)) +
  geom_boxplot() +
  geom_segment(data = df2, aes(y = ypos, yend = ypos, x = x, xend = xend,alpha=trans)) +
  geom_text(data = df2, aes(y = ypos*1.02, x = mean(c(x, xend)),label=label,alpha=trans))+
  facet_wrap( ~ gear,ncol=2, scales="free")
p

enter image description here


Solution

  • You are almost there. Just need to override the default range for the alpha scale, which is c(0.1, 1):

    p + scale_alpha(range = c(0, 1))
    

    plot