这是我在R中使用的代码(使用RGui 64位,R版本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")
答案 0 :(得分:1)
这将覆盖两个图形。我删除了额外的主标题和标签,因为它们也会被覆盖,看起来很乱。
# 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")