如何在 R 中将平均值添加到直方图中?
我想绘制一个带有平均值的直方图(例如,我们可以用蓝色粗线标记它)。
我尝试使用 plot
命令来完成此操作,但即使我设置了参数 add=TRUE
它不起作用。
I would like to plot a histogram with mean (average) value on it (e.g. we could mark it with a blue and bold line).
I tried to do it using plot
command, but even if I set the parameter add=TRUE
it didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
abline()
向绘图添加线条:另请参阅
?par
了解图形参数(例如col
和>lwd
)。一般来说,您还可以使用
lines()
绘制线条:其中
text()
用于添加文本。参数cex
描述了“字符扩展因子”。另外,请查看 Quick-R 了解以下内容的概述使用 R 进行基本绘图。
You can use
abline()
to add lines to a plot:Have also a look at
?par
for graphic parameters (likecol
andlwd
).In general, you can also plot lines using
lines()
:where
text()
is used for adding text. The argumentcex
describes the "character expansion factor".Also, have a look at Quick-R for an overview of basic plotting with R.
如果您有包含更多列的数据框,那么使用 ggplot2 包是我的首选:
Colname 是 data.frame 中您想要为其绘制直方图和平均值的列。
If you have data frames with more columns using of ggplot2 package is my preferred option:
Colname is column in your data.frame for which you would like to plot the histogram and mean.
我遇到了一个问题,即平均线没有出现,并且我没有收到任何错误来帮助我找出原因。我意识到没有发生任何事情,因为我缺少一些数据,因此平均值被计算为 NA。将
na.rm = T
添加到mean() arg 中得到了一个实数,并且出现了平均线。这是一个小疏忽和一个简单的修复,几乎不值得一写,但无论如何我都会发布它,以防它可以减轻某人的痛苦。I ran into a problem where the mean line wasn't appearing, and I wasn't getting any error to help me figure out why. I realized that nothing was happening because I had some missing data, so the mean was calculated as NA. Adding
na.rm = T
to the mean() arg got me a real number, and the mean line appeared. It's a small oversight and a simple fix hardly worth writing about, but I'm posting it anyway in case it might save someone some grief.