sim = 10000

x = rnorm(sim)
z = rnorm(sim)

y = (x>=0)*abs(z)-(x<0)*abs(z)

s = x+y
plot(x,y)

hist(s, freq = FALSE,main="X+Y")

hist(y)



library(ggplot2)

do.graphics.pdf = function(sp,title="", bins = 30){
  
  sp.mean=mean(sp)
  sp.sd = sd(sp)
  sp.median = median(sp)
  
  if (sp.mean <= sp.median) {
    d.mean = -0.2
    d.median = 0.1
  } else {
    d.mean = 0.1
    d.median = -0.2
  }
  
  
  
  e = ecdf(sp)
  x = knots(e)
  y.ecdf = e(x)
  y.norm = pnorm(x,mean = sp.mean, sp.sd)
  kernel.est = density(sp)
  y.dens = kernel.est["y"]$y
  x.dens = kernel.est["x"]$x
  y.pdf =  dnorm(x.dens,mean = sp.mean, sd=sp.sd)
  #h = hist(sp,probability = TRUE)  
  #y.hist = h$density
  
  df1 = data.frame(x,y.ecdf,y.norm)
  df2= data.frame(x.dens,y.dens,y.pdf)
  df.sp = data.frame(sp)
  
  p2 = ggplot(df.sp, aes(x=sp)) + 
    geom_histogram(aes(y=..density..),color="gray",alpha=0.1, bins = bins) +
    geom_density(aes(color="empirical")) +
    #stat_function(aes(colour = "Normal"),fun = dnorm, args = list(mean = sp.mean, sd = sp.sd)) +
    #scale_colour_manual("density", values = c("blue", "red"))+
    scale_colour_manual("density", values = c("darkgray"))+
    theme(legend.position="none") +
    geom_rug(data=df.sp, mapping=aes(x=sp), color="grey") +
    geom_vline(aes(xintercept=sp.mean),linetype="dashed", size=1, colour="green") +
    annotate("text", label = "Mean", x = sp.mean +d.mean, y = 0.3, colour = "green", angle = 90) +
    geom_vline(aes(xintercept=sp.median), linetype="dashed", size=1, colour="blue") +
    annotate("text", label = "Median", x = sp.median +d.median, y = 0.3, colour = "blue", angle = 90) 
  p2 = p2 + ggtitle(title)
  
  return(p2)
}

do.graphics.pdf(s)