8

I have a data frame and want to do a overlay density plot based on the two columns. I want the colors to be transparent. I have done this using the fill option and basically assigning fill to be a factor column. When you have a factor column by default all the fills going to be transparent.

But in a situation like this where there are no factors how do we fill it with transparent.

library("ggplot2")
vec1 <- data.frame(x=rnorm(2000, 0, 1))
vec2 <- data.frame(x=rnorm(3000, 1, 1.5))

ggplot() + geom_density(aes(x=x), fill="red", data=vec1) + 
  geom_density(aes(x=x), fill="blue", data=vec2)

I tried adding geom_density(alpha=0.4) but it didn't do any good. enter image description here

Jaap
  • 81,064
  • 34
  • 182
  • 193
add-semi-colons
  • 18,094
  • 55
  • 145
  • 232

1 Answers1

15

Like this?

ggplot() + geom_density(aes(x=x), fill="red", data=vec1, alpha=.5) + 
  geom_density(aes(x=x), fill="blue", data=vec2, alpha=.5)

EDIT Response to OPs comment.

This is the idiomatic way to plot multiple curves with ggplot.

gg <- rbind(vec1,vec2)
gg$group <- factor(rep(1:2,c(2000,3000)))
ggplot(gg, aes(x=x, fill=group)) + 
  geom_density(alpha=.5)+
  scale_fill_manual(values=c("red","blue"))

So we first bind the two datasets together, then add a grouping variable. Then we tell ggplot which is the grouping variable and it takes care of everything else.

jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • Is there a good way to label this density plots, I plan to plot more than two on top of each other – add-semi-colons May 21 '14 at 02:07
  • only issue here is data that i am plotting is in same row for example above density graphs would come from 001, 200, 100, -- 200 and 100 are columns are the density functions that case assigning group is hard. – add-semi-colons May 21 '14 at 02:41
  • 1
    Yes but your example is not like that. Read the documentation on `melt(...)` in the `reshape2` package. This is the way to convert from "wide" format - groups in different columns, to "long" format - all data in one column with the groups distinguished by a second column. – jlhoward May 21 '14 at 02:44
  • Can you adapt the code to apply the transparency only to front density? I am trying to replicate Figure 4 from [this paper](https://arxiv.org/pdf/2201.07072.pdf) (page. 27). – riccardo-df Jan 17 '23 at 10:17