2

I'm trying to visualize the histogram of two distributions and then visualize the distribution in the same pdf graph.

First of I'm trying to simulate 100 to 5000 draws from a normal distribution with µ = 6 och σ = 2.

Attempt:

x <-rnorm(n=100, mean=6, sd=2)
hist(x, probability=TRUE)
y <-rnorm(n=5000, mean=6, sd=2)
hist(x, probability=TRUE)

Which I belive to be correct for visualizing the histograms. However, I don't understand how to display the pdf of both graphs in the same graph. I found a function called pdfPlot() but couldn't make it work.

How do I combine x and y into one graph and show the pdf of them?

Agent smith 2.0
  • 112
  • 2
  • 12
  • Are you looking for `curve(dnorm(x, mean = 6, sd = 2), from = 0, to = 12, add = TRUE, col = "black", lty = "dashed")`? Or is it `lines(density(x))` and the same for `y`? – Rui Barradas Sep 16 '20 at 10:19

1 Answers1

1

Maybe an option for your consideration would be ggplot2. I will leave the code for you in case it is necessary. You can set your variables in a dataframe and then plot them. You can remove elements as position from geom_histogram() to have other perspectives in the plot. Here the code:

library(ggplot2)
set.seed(123)
#Code
x <-rnorm(n=100, mean=6, sd=2)
hist(x, probability=TRUE)
y <-rnorm(n=5000, mean=6, sd=2)
hist(x, probability=TRUE)
#Data
x <-rnorm(n=100, mean=6, sd=2)
y <-rnorm(n=5000, mean=6, sd=2)
xlab <- rep('x',100)
ylab <- rep('y',5000)
#Dataframe
df <- data.frame(value=c(x,y),lab=c(xlab,ylab),stringsAsFactors = F)
#Plot
ggplot(df,aes(x=value,fill=lab,color=lab,group=lab))+
  geom_histogram(aes(y = ..density..), alpha = 0.4,position = position_dodge())+
  geom_line(aes(y = ..density..,), stat = 'density',show.legend = F) 

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84