垂直线在ggplot中没有按预期显示

时间:2017-07-12 22:05:10

标签: r ggplot2 colors vline

我正在模拟40 i.i.d的手段的分布。指数和I绘制样本均值的分布以及样本均值(A)的分布均值和指数的理论均值(λ= 0.2(B))。两种方式A和B应显示为不同颜色的垂直线,其颜色代码应在图例中说明。但是,我的代码只生成一条垂直线,并忽略了我在代码中定义的颜色方案。

代码如下:

n <- 40

lambda <- 0.2

simulation = data.table(sample_mean = numeric())

for (i in (1 : 1000)){
  simulation <- rbind(simulation, data.table(sample_mean = mean(rexp(n,  lambda))))
}

#==============================================================================================
# Show the sample mean and compare it to the theoretical mean of the distribution.
#==============================================================================================

sample_mean <- mean(simulation$sample_mean)
4.981267

theoretical_mean <- 1/lambda
5

#------------------------------------------------------------------------------------------
# Plot of the Empirical and Theoretical Distributions and their respective means
#------------------------------------------------------------------------------------------

ggplot(simulation, aes(x = sample_mean) ) +
geom_histogram(aes(y=..density..), position="identity",alpha = 0.4, fill = "red", bins=100) +
  geom_density(colour = "red" , size = 2, alpha = 0.5) +
  geom_vline(xintercept = sample_mean, aes(colour = "Empirical"), size = 1.5, alpha =0.3) +
  geom_vline(xintercept = lambda, aes(colour = "Theoretical"), size = 1.5, alpha =0.3) +
  theme_economist() + ggtitle("Distribution of Sample Means.  Mean of the Empirical Distribution 
  and Mean of the Theoretical Exponential (1,000 simulations) ") +
  scale_colour_manual("Distributions", values = c("blue", "red")) +
  scale_y_continuous(name = "Density") +   
  scale_x_continuous(name = "Sample Means", breaks = seq(2, 8, .5), limits=c(2, 8))

情节如下:

enter image description here

您的建议将不胜感激。

==================================

修改

@mkt:谢谢你的贡献。我还需要在绘图中注释垂直线,这就是为什么我在aes()中使用了颜色,以及稍后在我的代码中映射到颜色的字符串。所以我仍然需要找到解决方法。

1 个答案:

答案 0 :(得分:0)

你有三个问题。 1)你正在绘制lambda,而不是1 / lambda 2)&#34;经验&#34; &#34;理论&#34;不是R会识别的颜色 3)颜色不应在aes()

中定义

这有效:

ggplot(simulation, aes(x = sample_mean) ) +
  geom_histogram(aes(y=..density..), position="identity",alpha = 0.4, fill = "red", bins=100) +
  geom_density(colour = "red" , size = 2, alpha = 0.5) +
  geom_vline(xintercept = sample_mean, colour = "blue", size = 1.5, alpha = 0.3) +
  geom_vline(xintercept = theoretical_mean, colour = "green", size = 1.5, alpha = 0.5) +
  ggtitle("Distribution of Sample Means.  Mean of the Empirical Distribution 
  and Mean of the Theoretical Exponential (1,000 simulations) ") +
  scale_colour_manual("Distributions", values = c("blue", "red")) +
  scale_y_continuous(name = "Density") +   
  scale_x_continuous(name = "Sample Means", breaks = seq(2, 8, .5), limits=c(2, 8))

enter image description here