Reputation: 122
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?
Upvotes: 2
Views: 3814
Reputation: 39605
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:
Upvotes: 1