我正在尝试在geom_rect
循环中使用for
,但是它不遵守我的限制。如果我在for
循环的上下文之外调用它,它将起作用。这是错误吗?还是我对geom_rect
不了解? outPlot_free
和outPlot1
应该相同(因为.2 = .2 / 1),但是outPlot1
中的矩形被截断,有趣的是,它们与outPlot2
相同,{ {1}}和outPlot3
。
outPlot4
library('ggplot2')
library('ggrepel')
sum_df <- data.frame(matrix(NA,nrow=10,ncol=3))
colnames(sum_df) <- c("Variable","Male","Female")
sum_df$Variable <- c("a","b","c","d","e","f","g","h","i","j")
covar = .7*.1*.1
Sigma = matrix(ncol=2,nrow=2,c(.2^2,covar,.2^2))
temp = eigen(Sigma)
SqrtSigma = temp$vectors%*%diag(sqrt(temp$values))%*%t(temp$vectors)
XYvec = c(0,0) + SqrtSigma%*%rnorm(2)
for(i in 1:10){
XYvec = c(0,0) + SqrtSigma%*%rnorm(2)
sum_df$Female[i] = XYvec[1]
sum_df$Male[i] = XYvec[2]
}
outPlot_free <- ggplot(sum_df,aes(x=Male,y=Female)) + theme_minimal() +
geom_rect(aes(xmin=-.2,xmax=.2,ymin=-Inf,ymax=Inf),fill="grey97",color=NA,alpha=.5,size=0) +
geom_rect(aes(ymin=-.2,ymax=.2,xmin=-Inf,xmax=Inf),size=0) +
geom_point() + geom_text_repel(aes(label=Variable)) +
scale_x_continuous(limits=c(-1,1),breaks=round(seq(-1,1,.1),digits=2)) +
scale_y_continuous(limits=c(-1,digits=2)) +
geom_abline(intercept=0,slope=1,linetype="dotdash",alpha=.5) +
scale_color_manual(values=c("grey60","black")) + xlab("Female") + ylab("Male") +
geom_hline(yintercept=.2,linetype="dashed",color="slateblue") + geom_vline(xintercept=.2,color="slateblue") +
geom_hline(yintercept=-.2,color="slateblue") + geom_vline(xintercept=-.2,color="slateblue")
for (q in 1:4) {
covar = .7*.1*.1
Sigma = matrix(ncol=2,.2^2))
temp = eigen(Sigma)
SqrtSigma = temp$vectors%*%diag(sqrt(temp$values))%*%t(temp$vectors)
XYvec = c(0,0) + SqrtSigma%*%rnorm(2)
for(i in 1:10){
XYvec = c(0,0) + SqrtSigma%*%rnorm(2)
sum_df$Female[i] = XYvec[1]
sum_df$Male[i] = XYvec[2]
}
outPlot <- ggplot(sum_df,y=Female)) + theme_minimal() +
geom_rect(aes(xmin=-.2/q,xmax=.2/q,size=0) +
geom_rect(aes(ymin=-.2/q,ymax=.2/q,size=0) +
geom_point() + geom_text_repel(aes(label=Variable)) +
scale_x_continuous(limits=c(-1,digits=2)) +
scale_y_continuous(limits=c(-1,digits=2)) +
geom_abline(intercept=0,alpha=.5) +
scale_color_manual(values=c("grey60","black")) + xlab("Female") + ylab("Male") +
geom_hline(yintercept=.2,color="slateblue") +
geom_hline(yintercept=-.2,color="slateblue")
assign(paste0("outPlot",q),outPlot)
}
outPlot_free
outPlot1
outPlot2
outPlot3
由reprex package(v0.3.0)于2019-11-09创建
outPlot4
和outPlot_free
除标绘点外应相同,因为它们是独立模拟的。