2015-06-21 18 views
2

在下面的代碼中,我構建了一個40x1000的數據框,其中每列中我都有來自參數lambda = 0.2的指數分佈的連續隨機抽取的累積平均值。 我添加了一個額外的列來承載「繪製」的具體數量。 我也計算行平均值作爲df_means。R - 如何覆蓋一組iid RV的平均值

如何在所有模擬房車上添加df_means(作爲黑線)?我不明白ggplot足夠做到這一點。

df <- data.frame(replicate(1000,cumsum(rexp(40,lambda))/(1:40))) 
df$draw <- seq(1,40) 
df_means <- rowMeans(df) 

Molten <- melt(df, id.vars="draw") 
ggplot(Molten, aes(x = draw, y = value, colour = variable)) + geom_line() + theme(legend.position = "none") + geom_line(df_means) 

我該如何在我的ggplot中添加陰謀(df_means,type =「l」)?

謝謝 1000 rexp iids

回答

1

你可以讓另一data.frame的手段和IDS並用它來畫線,

df_means <- rowMeans(df) 
means <- data.frame(id=1:40, mu=df_means) 

ggplot(Molten, aes(x=draw, y=value, colour=variable)) + 
    geom_line() + 
    theme(legend.position = "none") + 
    geom_line(data=means, aes(x=id, y=mu), color="black") 

enter image description here

0

如上所述here

stat_sum_df <- function(fun, geom="crossbar", ...) { 
    stat_summary(fun.data=fun, colour="red", geom=geom, width=0.2, ...) 
} 

k<-ggplot(Molten, aes(x = draw, y = value, colour = variable)) + geom_line() + theme(legend.position = "none") 
k+stat_sum_single(mean) #gives you the required plot 

enter image description here