我有以下代碼:
plot <- ggplot(data = df_sm)
geom_histogram(aes(x=simul_means, y=..density..), binwidth = 0.20, fill="slategray3", col="black", show.legend = TRUE)
plot <- plot labs(title="Density of 40 Means from Exponential Distribution", x="Mean of 40 Exponential Distributions", y="Density")
plot <- plot geom_vline(xintercept=sampl_mean,size=1.0, color="black", show.legend = TRUE)
plot <- plot stat_function(fun=dnorm,args=list(mean=sampl_mean, sd=sampl_sd),color = "dodgerblue4", size = 1.0)
plot <- plot geom_vline(xintercept=th_mean,size=1.0,color="indianred4",linetype = "longdash")
plot <- plot stat_function(fun=dnorm,args=list(mean=th_mean, sd=th_mean_sd),color = "darkmagenta", size = 1.0)
plot
我想顯示每一層的圖例,我試過 show.legend = TRUE 但它什么也沒做。
我所有的資料框都是來自指數分布模擬的平均值,我還有一些來自分布(平均值和標準偏差)的理論值,我將其描述為 th_mean 和 th_mean_sd。
我的模擬代碼如下:
lambda <- 0.2
th_mean <- 1/lambda
th_sd <- 1/lambda
th_var <- th_sd^2
n <- 40
th_mean_sd <- th_sd/sqrt(n)
th_mean_var <- th_var/sqrt(n)
simul <- 1000
simul_means <- NULL
for(i in 1:simul) {
simul_means <- c(simul_means, mean(rexp(n, lambda)))
}
sampl_mean <- mean(simul_means)
sampl_sd <- sd(simul_means)
df_sm<-data.frame(simul_means)
uj5u.com熱心網友回復:
如果你想得到一個圖例,你必須映射美學而不是設定顏色、填充、...作為引數,即color=...在里面移動aes(...)并利用scale_color/fill_manual來設定顏色值。就我個人而言,我發現使用一些有意義的標簽很有幫助,例如,在您的直方圖的情況下,我將標簽映射到"hist",fill但您可以使用任何您喜歡的標簽:
set.seed(123)
lambda <- 0.2
th_mean <- 1 / lambda
th_sd <- 1 / lambda
th_var <- th_sd^2
n <- 40
th_mean_sd <- th_sd / sqrt(n)
th_mean_var <- th_var / sqrt(n)
simul <- 1000
simul_means <- NULL
for (i in 1:simul) {
simul_means <- c(simul_means, mean(rexp(n, lambda)))
}
sampl_mean <- mean(simul_means)
sampl_sd <- sd(simul_means)
df_sm <- data.frame(simul_means)
library(ggplot2)
ggplot(data = df_sm)
geom_histogram(aes(x = simul_means, y = ..density.., fill = "hist"), binwidth = 0.20, col = "black")
labs(title = "Density of 40 Means from Exponential Distribution", x = "Mean of 40 Exponential Distributions", y = "Density")
stat_function(fun = dnorm, args = list(mean = sampl_mean, sd = sampl_sd), aes(color = "sampl_mean"), size = 1.0)
stat_function(fun = dnorm, args = list(mean = th_mean, sd = th_mean_sd), aes(color = "th_dens"), size = 1.0)
geom_vline(size = 1.0, aes(xintercept = sampl_mean, color = "sampl_mean"))
geom_vline(size = 1.0, aes(xintercept = th_mean, color = "th_mean"), linetype = "longdash")
scale_fill_manual(values = c(hist = "slategray3"))
scale_color_manual(values = c(sampl_dens = "dodgerblue4", th_dens = "darkmagenta", th_mean = "indianred4", sampl_mean = "black"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/354448.html
