我找到了多种在绘图中创建辅助y轴的方法,但我找不到在直方图中创建辅助y轴的方法。
以下是示例代码:
a <- sample(90:110, 50, replace=TRUE)
b <- runif(50, min=0, max=1)
hist(a)
lines(b)
b太小而无法显示在hist(a)
中,那么我是否可以在直方图中看到这两种方式?
答案 0 :(得分:1)
从技术上讲,解决方案可能与为方案in this answer提出的方法完全相同。这个想法是使用@ r2evans提出的两个图的重叠。
使用颜色编码是有意义的:
# set color rules
col_a <- "red"
col_b <- "darkblue"
col_common <- "black"
然后让我们绘制直方图和情节:
# draw a histogram first
par(mar = c(5, 5, 5, 5) + 0.3)
hist(a, col = col_a, axes = FALSE, xlab = "", ylab = "", main = "")
# add both axes with the labels
axis(side = 1, xlim = seq(along.with = b), col = col_a, col.axis = col_a)
mtext(side = 1, text = "a_value", col = col_a, line = 2.5)
axis(side = 2, col = col_a, col.axis = col_a, ylab = "")
mtext(side = 2, text = "a_Frequency", col = col_a, line = 2.5)
# ... and add an overlaying plot
par(new=TRUE)
plot(b, ylim = c(0, 1), axes = FALSE, col = col_b, type = "l", xlab = "", ylab = "")
points(b, col = col_b, pch = 20, xlab = "", ylab = "")
axis(side = 3, xlim = seq(along.with = b), col = col_b, col.axis = col_b)
mtext(side = 3, text = "b_index", col = col_b, line = 2.5)
axis(side = 4, ylim = c(0, 1), col = col_b, col.axis = col_b)
mtext(side = 4, text = "b_value", col = col_b, line = 2.5)
box(col = col_common)