如何在 R 中的直方图顶部叠加频率多边形



这是我在R中使用的代码(使用RGui 64位,R ver.3.3.1(来绘制数据直方图以及频率多边形。我没有使用 ggplot2。如何将频率多边形叠加在直方图的顶部,这样我就不必做两个单独的图形?也就是说,我希望绘制直方图,并在其顶部叠加频率多边形。

# declare your variables
data <- c(10, 7, 8, 4, 5, 6, 6, 9, 5, 6, 3, 8,
+ 4, 6, 10, 5, 9, 7, 6, 2, 6, 5, 4, 8, 7, 5, 6)
# find the range
range(data)
# establish a class width
class_width = seq(1, 11, by=2)
class_width
# create a frequency table
data.cut = cut(data, class_width, right=FALSE)
data.freq = table(data.cut)
cbind(data.freq)
# put both graphs together
par(mfrow=c(1,2))
# histogram of this data
hist(data, 
breaks=class_width, 
col="slategray3", 
border = "dodgerblue4",
right=FALSE,
xlab = "Scores", 
main = "Histogram of Quiz Data")
# create a frequency polygon for the birth weight data
plot(data.freq, type="b", 
xlab="Scores", 
ylab="Frequency",
add=TRUE,
main="A Frequency Polygon of Quiz")

这将覆盖两个图形。我已经删除了额外的主标题和标签,因为它们也会被覆盖,看起来很混乱。

# declare your variables
data <- c(10, 7, 8, 4, 5, 6, 6, 9, 5, 6, 3, 8,
+ 4, 6, 10, 5, 9, 7, 6, 2, 6, 5, 4, 8, 7, 5, 6)
# find the range
range(data)
# establish a class width
class_width = seq(1, 11, by=2)
class_width
# create a frequency table
data.cut = cut(data, class_width, right=FALSE)
data.freq = table(data.cut)
cbind(data.freq)
# put both graphs together
par(mfrow=c(1,2))
# histogram of this data
hist(data, 
breaks=class_width, 
col="slategray3", 
border = "dodgerblue4",
right=FALSE,
xlab = "Scores", 
main = "Histogram of Quiz Data")
# this is key to the overlay
par(new=TRUE)
# create a frequency polygon for the birth weight data
plot(data.freq, type="b")

最新更新