r - 将 geom_hline 添加到图例
问题描述
在昨天和今天都在网上搜索之后,我得到一个图例的唯一方法是在这篇文章中遵循“Brian Diggs”的解决方案: 将图例添加到 ggplot2 线图
这给了我以下代码:
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))
)
推荐阅读
- html - 从 UL 溢出的 Hoverable Dropdown
- python - 使用 --editable 引脚管理 src 文件夹的 pip 依赖项管理
- javascript - 更新功能未反映在本地存储中
- css - 绘制始终具有开始线和结束线的 CSS 网格线
- javascript - 我可以在组件中使用 redux 来避免道具钻孔吗?
- c++ - 为什么在声明之前是虚拟的,之后是覆盖?
- ios - 将 Swift Scenekit 中的多个 SCNObject 与圆柱体/路径连接起来
- python - 使用列表推导从列表中随机删除一个元素
- python - LookupError: 'hex' 不是文本编码;使用 codecs.encode() 处理任意编解码器
- node.js - 页面刷新时不会触发 React 客户端上的 Socket.io 断开连接