Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting normal distributions

I am trying to plot 3 examples of the normal distribution, however ggplot appears to be recognising the path as one continuous one rather than one stratified by the factor levels. I am relatively new to ggplot and any help would be greatly appreciated.

Here is my code:

set.seed(5872)

x<-seq(-7.5,7.5,0.1)
l<-length(x)*3
df<-data.frame(P=factor(rep(c("Mean: -1, SD: 0.5","Mean: 0, SD: 1","Mean: 1, SD: 1.5"),      each=l) ),
X=(c(x,x,x)), 
Y=(c(dnorm(x,-1,0.5),dnorm(x,0,1),dnorm(x,1,1.5))))

Normal<-ggplot(data=df,aes(X,Y,group=P,color=P))+
geom_path()+
scale_x_continuous("")+
scale_y_continuous("f(x)")+
scale_color_discrete("Parameters")+
ggtitle("Normal") + 
theme(plot.title = element_text(size=25,lineheight=.8, face="bold"))

How can I get ggplot to recognise the factors and plot with the 3 different colors? Rather than displaying one continuous path?

like image 846
Tom Avatar asked Jun 14 '13 06:06

Tom


People also ask

What graphs are used for normal distribution?

Because histograms display the shape and spread of distributions, you might think they're the best type of graph for determining whether your data are normally distributed. However, I'll show you how histograms can trick you! Normal probability plots are a better choice for this task and they are easy to use.


1 Answers

A reproducible example, using hint from bdemarest:

   library(ggplot2)

   set.seed(5872)

   x<-seq(-7.5,7.5,0.1)
   l<-length(x)
   df<-data.frame(P=factor(rep(c("Mean: -1, SD: 0.5","Mean: 0, SD: 1","Mean: 1, SD: 1.5"),
            each=l) ),
   X=(c(x,x,x)), 
   Y=(c(dnorm(x,-1,0.5),dnorm(x,0,1),dnorm(x,1,1.5))))

   Normal<-ggplot(data=df,aes(X,Y,group=P,color=P))+
   geom_path()+
   scale_x_continuous("")+
   scale_y_continuous("f(x)")+
   scale_color_discrete("Parameters")+
   ggtitle("Normal") + 
   theme(plot.title = element_text(size=25,lineheight=.8, face="bold"))

   print(Normal)
like image 173
Remko Duursma Avatar answered Oct 10 '22 00:10

Remko Duursma