如何在R中的直方图上同步频率多边形的轴?

时间:2017-03-22 19:47:49

标签: r rgui

previous question中,我询问如何在直方图上叠加频率多边形。那个问题解决了。我现在有一个不同的问题。我希望频率多边形的类标记位于每个直方图条的中间。 类标记是完全在类中间的值,通过平均直方图条的上下边界(a.k.a。,“classes”)找到。如果我绘制频率多边形,我只需在每个直方图类(或条形)的中间画一个点并连接点。但是,当我执行以下代码时,频率多边形是“展开”,并且没有与直方图相同的轴值。

# declare your variable
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)

# histogram of this data
hist(data, axes=TRUE,
breaks=class_width, col="slategray3",
border = "dodgerblue4", right=FALSE, 
xlab = "Scores", xaxp=c(1, 11, 10), 
yaxp=c(0, 12, 12), main = "Histogram and Frequency Polygon")

# paint the frequency polygon over the histogram
par(new=TRUE)

# create a frequency polygon for the data
plot(data.freq, axes=FALSE, type="b", ann=FALSE)

这是RGui产生的图像。我使用MS Paint绘制红线,表明我试图让R执行。这两个图似乎具有相同的y轴值。如何让两个图分享相同的x轴值?谢谢!

Histogram, Edited by MS Paint

1 个答案:

答案 0 :(得分:2)

如果查看hist(...)的(不可见)输出,您会看到几个可能有用的属性。值得注意的是:$mids。 (它们在?hist中定义明确。)

hist来电之前使用您的数据:

h <- hist(data, axes=TRUE,
    breaks=class_width, col="slategray3",
    border = "dodgerblue4", right=FALSE, 
    xlab = "Scores", xaxp=c(1, 11, 10), 
    yaxp=c(0, 12, 12), main = "Histogram and Frequency Polygon")
str(h)
# List of 6
#  $ breaks  : num [1:6] 1 3 5 7 9 11
#  $ counts  : int [1:5] 1 4 12 6 4
#  $ density : num [1:5] 0.0185 0.0741 0.2222 0.1111 0.0741
#  $ mids    : num [1:5] 2 4 6 8 10
#  $ xname   : chr "data"
#  $ equidist: logi TRUE
#  - attr(*, "class")= chr "histogram"

par(new=TRUE)无需添加一行:

lines(h$mids, data.freq)

如果这是必须使用par(new=TRUE)的简化示例,那么您需要做两件事:设置第二个xlim / ylim线,并给出适当的X点。 (你可能没有意识到,但第二个图是在这里推断出1:5的X值。只需plot(data.freq)即可看到。)

par(new = TRUE)
xlim <- range(class_width)
ylim <- c(0, max(h$counts))
plot(h$mids, data.freq, axes = FALSE, type = "b", ann = FALSE,
     xlim = xlim, ylim = ylim)