2017-09-12 50 views
0

我正在做一個蒙特卡羅模擬,其中我必須顯示在不同樣本大小的模擬在同一圖上的係數估計的密度。當使用scale_color_grey。我已將我的係數估計值放在同一個數據框中,樣本大小是一個因素。如果我用levels()來查詢因子,它的順序是正確的(從最小到最大的樣本量)。但是,下面的代碼給出的標度,其中所述順序是正確的在圖例中,但是從淺灰色的顏色移動到不正確的圖例排序與scale_color_grey()

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 

不使用breaks參數scale_color_grey在一個看似隨機的順序深灰色返回一個圖例其中陰影按正確順序排列,但不會從最小到最大樣本量增加。

這是怎麼回事?據我瞭解,ggplot2應該在分配顏色和創建圖例時遵循該因子的順序(這是正確的)。我怎樣才能使傳說和從最小到最小樣本量的灰度增加?

回答

1

你應該讓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 

無需手動子集數據。