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

梦想的初衷 提交于 2019-12-08 03:22:08

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/42937192/how-do-i-superimpose-a-frequency-polygon-on-top-of-a-histogram-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!