我试图使用以下数据集在R中重现直方图:
ages <- c(26, 31, 35, 37, 43, 43, 43, 44, 45, 47, 48, 48, 49, 50, 51, 51, 51, 51, 52, 54, 54, 54, 54,
55, 55, 55, 56, 57, 57, 57, 58, 58, 58, 58, 59, 59, 62, 62, 63, 64, 65, 65, 65, 66, 66, 67,
67, 72, 86)
我希望直方图看起来尽可能接近这个:
但是,我有三个问题:
我读过?hist
并认为前两个问题可以通过设置xlim
和ylim
来完成,但这似乎无法正常工作。
我为第三个问题感到茫然,因为我认为可以通过加入breaks = c(25.5, 34.5, 43.5, 52.5, 61.5, 70.5, 79.5, 88.5)
来实现。
到目前为止,这是我的代码:
hist(ages, breaks = c(25.5, 34.5, 43.5, 52.5, 61.5, 70.5, 79.5, 88.5), freq=TRUE, col = "lightblue",
xlim = c(25.5, 88.5), ylim = c(0,18), xlab = "Age", ylab = "Frequency")
接下来是我相应的直方图:
赞赏正确方向的任何碰撞。提前谢谢。
答案 0 :(得分:10)
在您的数据中,您似乎在52.5和61.5之间的类别中最多有17个数字。这甚至是双方的开放时间间隔:
ages <- c(26, 31, 35, 37, 43, 43, 43, 44, 45, 47, 48, 48, 49, 50, 51, 51, 51,
51, 52, 54, 54, 54, 54, 55, 55, 55, 56, 57, 57, 57, 58, 58, 58, 58,
59, 59, 62, 62, 63, 64, 65, 65, 65, 66, 66, 67, 67, 72, 86
)
sum(ages >= 52.5 & ages <= 61.5)
[1] 17
所以直方图只能反映出来。
为此您可能对 THIS SO ANSWER
感兴趣如果您阅读help(hist)
,您会看到中断指定了这些组的形成点:
... *给出直方图单元格之间断点的向量
所以你打算按计划打破工作。你遇到的问题是在x轴上显示相同的数字。 ANOTHER SO ANSWER 可能会对您有所帮助。
以下是如何重现情节。
library(plotrix) # for the break on x axis
library(shape) # for styled arrow heads
# manually select axis ticks and colors
xticks <- c(25.5, 34.5, 43.5, 52.5, 61.5, 70.5, 79.5, 88.5)
yticks <- seq(2, 18, 2)
bgcolor <- "#F2ECE4" # color for the background
barcolor <- "#95CEEF" # color for the histogram bars
# top level parameters - background color and font type
par(bg=bgcolor, family="serif")
# establish a new plotting window with a coordinate system
plot.new()
plot.window(xlim=c(23, 90), ylim=c(0, 20), yaxs="i")
# add horizontal background lines
abline(h=yticks, col="darkgrey")
# add a histogram using our selected break points
hist(ages, breaks=xticks, freq=TRUE, col=barcolor, xaxt='n', yaxt='n', add=TRUE)
# L-shaped bounding box for the plot
box(bty="L")
# add x and y axis
axis(side=1, at=xticks)
axis(side=2, at=yticks, labels=NA, las=1, tcl=0.5) # for inward ticks
axis(side=2, at=yticks, las=1)
axis.break(1, 23, style="zigzag", bgcol=bgcolor, brw=0.05, pos=0)
# add labels
mtext("Age", 1, line=2.5, cex=1.2)
mtext("Frequency", 2, line=2.5, cex=1.2)
# add arrows
u <- par("usr")
Arrows(88, 0, u[2], 0, code = 2, xpd = TRUE, arr.length=0.25)
Arrows(u[1], 18, u[1], u[4], code = 2, xpd = TRUE, arr.length=0.25)
图片: