34

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

Ali
  • 9,440
  • 12
  • 62
  • 92
  • 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 Jan 19 '13 at 05:09

1 Answers1

38

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", size=2, alpha=0.4)

Ceci n'est pas une pipe

Eric Fail
  • 8,191
  • 8
  • 72
  • 128
  • 1
    how to do this on other geom? Any idea? – Indranil Gayen Feb 07 '19 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 Feb 10 '19 at 08: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: https://github.com/tidyverse/ggplot2/blob/HEAD/R/aes-colour-fill-alpha.r). – Dan Tarr Apr 13 '22 at 18:31