我在R中使用了一些代码。我试图在同一个图中创建6个不同的直方图。它工作正常,但我需要在6个直方图的每一个中放置1条垂直线。我正在使用的代码可能如下所示:
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)
问题出在语句geom_vline(xintercept = z, colour = "black")
上。显然,不是在每个直方图中放置一条垂直线,而是在每个直方图中放置所有6条线。所以相反,我希望z中的第一个元素在第一个直方图中形成一条垂直线,z中的第二个元素在第二个直方图中形成一条垂直线,所以第四个。
由于
答案 0 :(得分:6)
对于定义构面的变量的每个值,您的z
必须是data.frame
,并且具有相应的xintercept
。尝试这些更改:
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)
我希望有所帮助。
答案 1 :(得分:4)
您在数据之外有z
,因此您将在每个方面绘制一条垂直线。使用
df2 <- (merge(df2, cbind.data.frame(variable=names(df), z)))
然后
geom_vline(aes(xintercept = z), colour="black")