xsonic
xsonic

Reputation: 21

How to plot 3 density functions in one graph in R?

I am trying to draw 3 graphs in R studio. Mean = 90, standard deviation = 5, Mean = 90, standard deviation = 2, Mean = 90, standard deviation = 1.

I Know how to draw one graph, using following syntax,

x   <- seq(1,180)
y   <- dnorm(x,mean=90, sd=25)
plot(x,y, type="l", lwd=1)

but not sure how to add another two graphs.

Upvotes: 1

Views: 653

Answers (2)

Severin Pappadeux
Severin Pappadeux

Reputation: 20130

Alternative plotting using ggplot2 package

library(ggplot2)

p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))
p <- p + stat_function(fun = function(x) dnorm(x, mean = 90, sd = 5))
p <- p + stat_function(fun = function(x) dnorm(x, mean = 90, sd = 2))
p <- p + stat_function(fun = function(x) dnorm(x, mean = 90, sd = 1))
p <- p + xlim(82.0, 98.0) + ylim(0.0, 0.5)
print(p)

Three gaussians

Upvotes: 0

steveb
steveb

Reputation: 5532

You could do something like the following

x <- seq(1,180)
plot( x, dnorm(x, mean = 90, sd = 5), type="l", lwd=1, ylim = c(0, 0.6))
lines(x, dnorm(x, mean = 90, sd = 2), type="l", lwd=1)
lines(x, dnorm(x, mean = 90, sd = 1), type="l", lwd=1)

If you don't set ylim correctly, the subsequent data may not appear on the plot.

Here is the result below

enter image description here

Upvotes: 1

Related Questions