再现R中直方图的风格

3 plot r histogram

我正在尝试使用以下数据集来重现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)
Run Code Online (Sandbox Code Playgroud)

我想让直方图看起来尽可能接近这个:

在此输入图像描述

但是,我有三个问题:

  1. 我无法在y轴上获得频率计数达到18
  2. 我无法在x轴上获得波浪形断裂符号
  3. 我的休息似乎没有正确设置到我在代码中输入的向量

我读了?hist,并认为前两个问题可以通过设置来完成xlimylim,但似乎并不奏效.

我对第三个问题感到茫然,因为我认为可以通过包含来实现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")
Run Code Online (Sandbox Code Playgroud)

接下来是我相应的直方图:

在此输入图像描述

任何正确方向的碰撞都是值得赞赏的.提前致谢.

Kar*_*ius 10

1.达到18.

看来,在您的数据中,您在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
Run Code Online (Sandbox Code Playgroud)

所以你的直方图只能反映出来.

2.打破符号.

对于你可能有兴趣在此这样,请回答

3.休息.

如果您阅读,help(hist)您将看到中断指定了组形成的点:

...*给出直方图单元格之间断点的向量

所以你打算按计划打破工作.你遇到的问题是在x轴上显示相同的数字.在这里,另一个答案可能会帮助你.

以下是如何重现情节的方法.

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)
Run Code Online (Sandbox Code Playgroud)

和图片:

结果

  • 如果这不是一个关于基础绘图效益的好广告,我不知道是什么. (2认同)