将 geom_hline 添加到图例

Add geom_hline to legend

昨天和今天在网上搜索之后,我得到图例的唯一方法是按照 'Brian Diggs' 在这个 post 中的解决方案: Add legend to ggplot2 line plot

这给了我以下代码:

library(ggplot2)
ggplot()+
  geom_line(data=myDf, aes(x=count, y=mean, color="TrueMean"))+
  geom_hline(yintercept = myTrueMean, color="SampleMean")+
  scale_colour_manual("",breaks=c("SampleMean", "TrueMean"),values=c("red","blue"))+
  labs(title = "Plot showing convergens of Mean", x="Index", y="Mean")+
  theme_minimal()

如果我删除 hline 的颜色,一切正常,但如果我在 hline 的颜色中添加一个不是实际颜色的值(如 "SampleMean" ) 我得到一个错误,它不是一种颜色(仅适用于 hline)。 增加一个传奇这么普通的东西怎么会是这么大的问题呢?还有更简单的方法吗?

要创建原始数据:

#Initial variables
myAlpha=2
myBeta=2
successes=14
n=20
fails=n-successes

#Posterior values
postAlpha=myAlpha+successes
postBeta=myBeta+fails

#Calculating the mean and SD
myTrueMean=(myAlpha+successes)/(myAlpha+successes+myBeta+fails)
myTrueSD=sqrt(((myAlpha+successes)*(myBeta+fails))/((myAlpha+successes+myBeta+fails)^2*(myAlpha+successes+myBeta+fails+1)))

#Simulate the data
simulateBeta=function(n,tmpAlpha,tmpBeta){
  tmpValues=rbeta(n, tmpAlpha, tmpBeta)
  tmpMean=mean(tmpValues)
  tmpSD=sd(tmpValues)
  returnVector=c(count=n, mean=tmpMean, sd=tmpSD)
  return(returnVector)
}

#Make a df for the data
myDf=data.frame(t(sapply(2:10000, simulateBeta, postAlpha, postBeta)))

给定的解决方案适用于大多数情况,但不适用于 geom_hline (vline)。对于它们,您通常不必使用 aes,但是当您需要生成图例时,您必须将它们包装在 aes:

library(ggplot2)
ggplot() +
  geom_line(aes(count, mean, color = "TrueMean"), myDf) +
  geom_hline(aes(yintercept = myTrueMean, color = "SampleMean")) +
  scale_colour_manual(values = c("red", "blue")) +
  labs(title = "Plot showing convergens of Mean",
       x = "Index",
       y = "Mean",
       color = NULL) +
  theme_minimal()


查看原始数据,您可以使用 geom_point 进行更好的可视化(还添加了一些主题更改):

ggplot() +
  geom_point(aes(count, mean, color = "Observed"), myDf,
             alpha = 0.3, size = 0.7) +
  geom_hline(aes(yintercept = myTrueMean, color = "Expected"),
             linetype = 2, size = 0.5) +
  scale_colour_manual(values = c("blue", "red")) +
  labs(title = "Plot showing convergens of Mean",
       x = "Index",
       y = "Mean",
       color = "Mean type") +
  theme_minimal() +
  guides(color = guide_legend(override.aes = list(
    linetype = 0, size = 4, shape = 15, alpha = 1))
  )