Overlay 10 density plots in R with colour proportional to number of overlapping plots
Asked Answered
P

1

7

I have a dataset with 224900 observations and 10 variables which are the result of different Taylor series back transformations to original data values. I wish to overlay the density plots of each of these 10 variables to show the level of robustness of the Taylor series back transformation on the data estimates. Rather than having just 10 lines, I thought it would be good to have a colour apply, so that each density plot contributes 10% of a grey scale. Where there is data that just relates to one of the plots, there would be 10% grey, two plots would be twice as dark at 20%, up to where all the density plots overlap, which would be 100%.

I have used melt to get a dataframe that is 2249000 rows long. There are three columns, the first is the person ID, the second is the grouping variable (variable), and the third is the value of daily kJ intake (value).

I have used the following code to overlay the density plots in ggplot2 but it uses different colours for the groups. How can I change this code to get my grey scale? I want all 10 groups to have the same colour and colour density; the purpose of the plot is simply to to visually show the amount of overlap on the density plot using greyscale.

ggplot(Energy, aes(x=value, fill=variable)) + geom_density(alpha = 0.5)

Some test data to play with for those wishing to help, using 5 groups and not 10:

variable <- c(rep("A",100), rep("B",100), rep("C",100), rep("D",100), rep("E",100))
value <- c(rnorm(100,5000,200), rnorm(100,5050,210), rnorm(100,5100,215), 
           rnorm(100,5150,220), rnorm(100,5200,225))
MyData <- cbind.data.frame(value, variable)
ggplot(MyData, aes(x=value, fill=variable)) + geom_density(alpha = 0.5)

I think the answer may be associated with modifying scale_colour_grey and/or scale_manual but I don't understand enough to work this out myself.

Pussy answered 17/10, 2012 at 22:25 Comment(0)
H
9

This can be done by using a group aesthetic and making the fill for the density a light shade of grey like gray10 or gray20:

ggplot(MyData, aes(x=value, group=variable)) + geom_density(alpha = 0.5, fill="gray20")

Which will give you:

Density plot

In your case you probably want gray10, since you have 10 groups, rather than the 5 that are plotted here.

Heyman answered 17/10, 2012 at 22:46 Comment(1)
Thank you, that's exactly what I wanted. I changed the fill="gray20" to fill="gray10" for my 10-group "proper" data set and it works perfectly!Pussy

© 2022 - 2024 — McMap. All rights reserved.