如何使用线条将频率多边形叠加在 R 中的直方图之上?

How do I superimpose a frequency polygon on top of a histogram in R using lines?

我是 R 和 RStudio 的初学者,我正在尝试使用 "cars" 数据集在直方图之上制作频率多边形。

attach(cars)
hist(speed)
lines(speed, lwd=2, col = "royalblue")

This is the output I'm getting.

我需要的是正确显示在直方图顶部的点。我已经看到 但我无法在我的代码中使用它。

This is the output I need (It's an example)

hist() 有一个隐藏的输出,你可以通过赋值获取它。然后用它喂lines()

h <- hist(x, col=5)
lines(x=c(0, h$mids, tail(h$mids, 1) + el(diff(h$mids))), y=c(0, h$counts, 0), lwd=2)


数据:

set.seed(22522)
x <- rpois(50, 6)

尝试

par(mfrow=c(2,2))
hist(speed)
lines(speed, lwd=2, col = "royalblue")

或者,您可以在 ggplot2 中一次完成所有操作。但我需要一个数据样本和您的脚本。

最佳