[英]Incorrect Legend Ordering with scale_color_grey()
我正在做一個蒙特卡洛模擬,其中我必須顯示同一圖上具有不同樣本大小的模擬的系數估計密度。 使用scale_color_grey
。 我將系數估計值放在同一數據框中,並將樣本大小作為一個因素。 如果我使用levels()
查詢因子,則其順序正確(從最小到最大樣本大小)。 但是,以下代碼給出了一個比例,其中圖例中的順序是正確的,但是顏色以看似隨機的順序從淺灰色變為深灰色
montecarlo <- function(N, nsims, nsamp){
set.seed(8675309)
coef.mc <- vector()
for(i in 1:nsims){
access <- rnorm(N, 0, 1)
health <- rnorm(N, 0, 1)
doctorpop <- (access*1) + rnorm(N, 0, 1)
sick <- (health*-0.4) + rnorm(N, 0, 1)
insurance <- (access*1) + (health*1) + rnorm(N, 0, 1)
healthcare <- (insurance*1) + (doctorpop*1) + (sick*1) + rnorm(N, 0, 1)
data <- as.data.frame(cbind(healthcare, insurance, sick, doctorpop))
sample.data <- data[sample(nrow(data), nsamp), ]
model <- lm(data=sample.data, healthcare ~ insurance + sick + doctorpop)
coef.mc[i] <- coef(model)["insurance"]
}
return(as.data.frame(cbind(coef.mc, nsamp)))
}
sample30.df <- montecarlo(N=1000, nsims=1000, nsamp=30)
sample100.df <- montecarlo(1000,1000,100)
sample200.df <- montecarlo(1000, 1000, 200)
sample500.df <- montecarlo(1000, 1000, 500)
sample1000.df <- montecarlo(1000, 1000, 1000)
montecarlo.df <- rbind(sample30.df, sample100.df, sample200.df, sample500.df, sample1000.df)
montecarlo.df$nsamp <- as.factor(montecarlo.df$nsamp)
levels(montecarlo.df$nsamp) <- c("30", "100", "200", "500", "1000")
##creating the plot
montecarlo.plot <- ggplot(data=montecarlo.df, aes(x=coef.mc, color=nsamp))+
geom_line(data = subset(montecarlo.df, nsamp==30), stat="density")+
geom_line(data = subset(montecarlo.df, nsamp==100), stat="density")+
geom_line(data = subset(montecarlo.df, nsamp==200), stat="density")+
geom_line(data = subset(montecarlo.df, nsamp==500), stat="density")+
geom_line(data = subset(montecarlo.df, nsamp==1000), stat="density")+
scale_color_grey(breaks=c("30", "100","200", "500", "1000"))+
labs(x=NULL, y="Density of Coefficient Estimate: Insurance", color="Sample Size")+
theme_bw()
montecarlo.plot
不對scale_color_grey
使用breaks
參數將返回圖例,其中陰影以正確的順序排列,但不會從最小樣本大小增加到最大樣本大小。
這里發生了什么? 據我了解, ggplot2
在分配顏色和創建圖例時應遵循該因素的順序(正確)。 如何使圖例和灰色陰影從最小樣本大小增加到最小樣本大小?
您應該讓ggplot
來為nsamp
每個級別繪制單獨的線條:因為您已將nsamp
映射到色彩美學, ggplot
會為每個級別自動繪制不同的線條,因此您可以執行以下操作:
montecarlo.plot <- ggplot(data=montecarlo.df, aes(x=coef.mc, color=nsamp))+
geom_line(stat = "density", size = 1.2) +
scale_color_grey() +
labs(x=NULL, y="Density of Coefficient Estimate: Insurance", color="Sample Size")+
theme_bw()
montecarlo.plot
無需手動子集數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.