Ewa Wanat
Ewa Wanat

Reputation: 13

How to make schematic density curves in r?

I'm trying to make schematic density curves, just to represent idea. I tried the following code:

This isn't based on any actual data, I just need a nice image.

green1 <- rnorm(n=10000, mean=6, sd = .5)
green2 <- rnorm(n=10000, mean=18, sd = .5)
green3 <- rnorm(n=10000, mean=30, sd = .5)
green <- c(green1, green2, green3)

red1 <- rnorm(n=10000, mean=-2, sd = .01)
red2 <- rnorm(n=10000, mean=2, sd = .01)
red3 <- rnorm(n=10000, mean=10, sd = .01)
red4 <- rnorm(n=10000, mean=14, sd = .01)
red5 <- rnorm(n=10000, mean=22, sd = .01)
red6 <- rnorm(n=10000, mean=26, sd = .01)

red <- c(red1, red2, red3, red4, red5, red6)

plot(density(green), col= 'blue', xlim=c(-5,35))
lines(density(red), col= 'red')

But the red curves in between the peaks aren't always touching the 0 line, and changing the sd to something smaller doesn't make a difference. Can anyone help please?

Thanks so much!

Upvotes: 1

Views: 28

Answers (1)

G5W
G5W

Reputation: 37641

The problem is not with your sd. It is the way that the bandwidth is computed for the density function. Because the range of the data is so wide, density uses a wide band which makes two adjacent distributions overlap. You need to reduce the bandwidth by using the adjust parameter. Here is your code with only minor changes. You can even make the red sd be bigger and this will work.

plot(density(green), col= 'blue', xlim=c(-5,35), ylim=c(0,0.14))
lines(density(red, adjust=0.5), col= 'red')

Density curves with reduced bandwidth

Upvotes: 1

Related Questions