36

How to change the transparency level of lines in ggplot() diagram (i.e. histogram, line plot, etc.)?

For instance consider the code below:

data <- data.frame(a=rnorm(100), b = rnorm(100,.5,1.2))
data <- melt(data)
colnames(data) <- c("Category", "Intensity")
p <- ggplot(data, aes(x=Intensity))
p <- p + geom_density(aes(color=Category), size=2, alpha=.4)
print(p)

I expected the lines would be transparent (as alpha=.4), but they're not.

enter image description here

1
  • 7
    geom_density uses alpha for the fill aesthetic. If you don't want a fill, use geom_line(aes(color=Category), stat="density", alpha=0.4) instead.
    – baptiste
    Commented Jan 19, 2013 at 5:09

1 Answer 1

41

Simply following @baptiste's directions,

data <- data.frame(a=rnorm(100), b = rnorm(100,.5,1.2))
data <- melt(data)
colnames(data) <- c("Category", "Intensity")
p <- ggplot(data, aes(x=Intensity))
p + geom_line(aes(color=Category), stat="density", linewidth=2, alpha=0.4)

Ceci n'est pas une pipe

3
  • 1
    how to do this on other geom? Any idea? Commented Feb 7, 2019 at 13:00
  • 1
    You should ask a new question. Try to show what you have tried and if possible you should strive to be specific. Cheers!
    – Eric Fail
    Commented Feb 10, 2019 at 8:50
  • 1
    In reference to Indranil's question: For opacity - use "alpha=n" where n is from 0 (transparent) to 1 (solid) - available on almost any geom element. Can alternately add opacity to RGB specification in "colour" (or "fill") using "colour=#rrggbbAA" where AA is from 00 (transparent) to FF (solid). (see: github.com/tidyverse/ggplot2/blob/HEAD/R/…).
    – Dan Tarr
    Commented Apr 13, 2022 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.