将geom_hline添加到图例

时间:2019-03-30 07:59:28

标签: r ggplot2 geom-hline

在昨天和今天都在网上搜索后,我得到一个传奇人物的唯一方法是遵循这篇文章中“ Brian Diggs”的解决方案: 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)))

1 个答案:

答案 0 :(得分:1)

给出的解决方案在大多数情况下都适用,但不适用于geom_hlinevline)。对于它们,通常不必使用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()

enter image description here


看到原始数据,您可以使用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))
  )

enter image description here