如何在R中的直方图上方叠加频率多边形? [英] How do I superimpose a frequency polygon on top of a histogram in R?

查看:156
本文介绍了如何在R中的直方图上方叠加频率多边形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is the code I used in R (using RGui 64-bit, R ver. 3.3.1) to plot a histogram of data along with a frequency polygon. I am not using ggplot2. How can I superimpose the frequency polygon on top of the histogram so that I don't have to do two separate graphs? That is, I want the histogram plotted, with the frequency polygon overlaid on top of it.

# 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")

推荐答案

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

This will overlay the two graphs. I've removed the extra main title and labels, since they would also be overlayed, which looks messy.

# 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")

这篇关于如何在R中的直方图上方叠加频率多边形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆