Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical line in histogram in r

Tags:

r

ggplot2

I'm struggeling a bit with a peace of code in R. I am trying to create 6 different histograms in the same figure. It works fine, but I need to place 1 vertical line in each of the 6 histograms. The code I am working with could look something like this:

require(ggplot2)
require(reshape2)
require(gdata)

MC_beta=rbind(rnorm(1000,-2,0.1),rnorm(1000,-1,0.1),rnorm(1000,0,0.1),rnorm(1000,0.5,0.1),rnorm(1000,1,0.1),rnorm(1000,2,0.1))


df <- data.frame(MC_beta[1,], MC_beta[2,], MC_beta[3,], MC_beta[4,],MC_beta[5,],MC_beta[6,])
names(df)[1:6]<-c("1", "2", "3", "4","5","6")

df2 = melt(df)

z=c(-2,-1,0,0.5,1,2)

ggplot(df2, aes(x=value, fill = variable)) + geom_vline(xintercept = z, colour="black") +geom_histogram(binwidth=0.03,colour = "black") + scale_fill_manual(name = "",values = c('red','blue',"red","blue","red","blue")) +
  facet_wrap(~variable,nrow=6, ncol=1) + scale_x_continuous(breaks=seq(-2.5,2.5,0.5)) + guides(fill=FALSE) +
  theme_bw() + theme(strip.background = element_blank(),axis.text=element_text(size=14.5),strip.text.x = element_text(size = 14.5)) + stat_function(fun = dnorm)

The problem is with the statement geom_vline(xintercept = z, colour = "black"). Apparently instead of placing one vertical line in each histogram, it places all 6 lines in each histogram. So instead, I want the first element in z to make a vertical line in the first histogram, the second element in z to make a vertical line in the second histogram and so fourth.

Thanks

like image 810
Ku-trala Avatar asked Dec 14 '22 23:12

Ku-trala


2 Answers

Your z needs to be a data.frame with the corresponding xintercept for every value of the variable that defines the facet. Try these changes:

z <- data.frame(variable=levels(df2$variable), 
                mean=c(-2,-1,0,0.5,1,2))

ggplot(df2, aes(x=value, fill = variable))+ 
  geom_vline(data=z, aes(xintercept = mean), colour="black") +
  geom_histogram(binwidth=0.03,colour = "black") + 
  scale_fill_manual(name = "",values = c('red','blue',"red","blue","red","blue")) +
  facet_wrap(~variable,nrow=6, ncol=1) + 
  scale_x_continuous(breaks=seq(-2.5,2.5,0.5))+ guides(fill=FALSE) +
  theme_bw() + 
  theme(strip.background = element_blank(), axis.text=element_text(size=14.5), strip.text.x = element_text(size = 14.5)) + 
  stat_function(fun = dnorm)

I hope that helps.

like image 165
ilir Avatar answered Dec 17 '22 13:12

ilir


You have z outside the data, so you will draw a vertical line in each facet. Use

df2 <- (merge(df2, cbind.data.frame(variable=names(df), z)))

and then

geom_vline(aes(xintercept = z), colour="black")
like image 36
shadow Avatar answered Dec 17 '22 11:12

shadow