我们先生成数据和hist对象:
set.seed(0) ## added for reproducibility
g <- rnorm(2000, 5, 1)
h <- hist(g, breaks = 50, plot = FALSE)
我暂时抑制了plot = FALSE 的绘图。
问题是,我们想要两个 y 轴:
基本上我们在两个轴上的密度值处添加刻度线,但是
hist 对象中的密度值为h$density。对于漂亮的图表,我们申请
pretty() 获取刻度线位置:
pos <- pretty(h$density, n = 5)
# [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6
要在pos 找到相应的计数,我们这样做:
freq <- round(pos * length(g) * with(h, breaks[2] - breaks[1]))
# [1] 0 20 40 60 80 100 120
这里使用的round()只是为了确保丢弃有限精度计算引入的数字,以便我们以整数结束。
现在我们已准备好生成集成直方图。记得增加右边距,为右轴的轴名预留一些空间。下面我们设置右边距和左边距一样。
new.mai <- old.mai <- par("mai")
new.mai[4] <- old.mai[2]
par(mai = new.mai)
graphics:::plot.histogram(h, freq = FALSE, col="bisque", main="Integrated Histogram",
xlab = paste0("Cr","(mg/dL)"), ylab="Frequeny",
border="black", yaxt='n')
Axis(side = 2, at = pos, labels = freq)
Axis(side = 4, at = pos, labels = pos)
mtext("Density", side = 4, line = 3)
lines(density(g), col="dimgray")
par(mai = old.mai)
注意我如何使用graphics:::plot.histogram 绘制hist 对象,并使用mtext 在边距上添加文本。阅读?plot.histogram 和?mtext 了解更多信息。