【问题标题】:Creating a secondary y-axis in histogram在直方图中创建辅助 y 轴
【发布时间】:2018-03-07 08:25:45
【问题描述】:

我找到了多种在绘图中创建辅助 y 轴的方法,但我找不到在直方图中创建辅助 y 轴的方法。

这是一个示例代码:

a <- sample(90:110, 50, replace=TRUE)
b <- runif(50, min=0, max=1)
hist(a)
lines(b)

b 太小而无法在hist(a) 中显示,所以有什么方法可以在直方图中看到两者?

【问题讨论】:

  • 我不知道你打算在这里展示什么。您是否期望b (U~[0,1]) 中的随机值以某种方式直观地映射到从 90-110 的 x 轴或从 0 到 14 左右的 y 轴映射?也许你需要像par(new=TRUE) 这样的东西并在旧的情节上覆盖一个新的情节。 (提示:这有点太模糊了,请以您预期的输出形式提供清晰的说明。)
  • 不完全正确,@RolandASc,在上面的hist 之后尝试lines(c(rep(0,90),5,10,5))。如果是单个向量,则假定向量为yx=seq_along(y)
  • @r2evans,感谢您的澄清。我的目标是在直方图(a)上添加一条指导线 b。由于 b 的值太小,所以我需要为 b 创建第二个 y 轴。
  • 我不确定什么是引导线,你的意思是连接每个柱状图的顶部吗?或者描述数据的其他一些(外部,这里)属性的行?你如何将ba 联系起来?

标签: r histogram yaxis


【解决方案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)

【讨论】:

  • 谢谢。这就是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多