第二个 y 轴与数据不对齐

时间:2021-05-12 23:19:45

标签: r ggplot2

我需要使用两个 y 轴在一个图形上绘制两组数据。我无法在第二个 y 轴上正确地进行数据/轴标签转换。

示例:

library(dplyr)
library(ggplot2)
library(scales)

# example data
df <- structure(list(x = c(25, 30, 31, 32, 33, 34, 35, 36.5, 38, 40, 
42, 44, 46, 51, 53, 55, 58, 60, 62, 66, 69.5, 73.5, 80.5, 88, 
97), y = c(25L, 6L, 8L, 1L, 1L, 0L, 4L, 0L, 2L, 4L, 1L, 1L, 11L, 
0L, 0L, 6L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L), y2 = c(281.8, 
283.4, 284.8, 286.3, 288, 289.8, 291.7, 294.4, 296.9, 299.6, 
301.8, 303.8, 305, 305.7, 305.1, 304.3, 302.2, 300.5, 298.8, 
295.1, 292.4, 289.6, 286, 283.6, 281.9)), row.names = c(NA, -25L
), class = "data.frame")

# transform data to be plotted on the second y-axis 
df$y2_trans <- rescale(df$y2, to = c(min(df$y), max(df$y)))

# plot 
ggplot (data = df, aes(x = x)) +
  geom_point(aes(x, y)) +
  geom_line(aes(x = x, y = y2_trans), color = "red") +
  geom_point(aes(x = x, y = y2_trans), color = "red") +
  scale_y_continuous(sec.axis = sec_axis(~rescale(., to = c(min(df$y2), max(df$y2)))))

enter image description here

从表面上看,这看起来不错,但仔细检查红色点和线,与它们在第二个 y 轴上的位置不太匹配,例如

df[14,]
    x y    y2 y2_trans
14 51 0 305.7       25

曲线上的最高点应该在第二个 y 轴上的 305.7,但它刚好低于 305。我可以看到这是与我使用 scales::rescale 相关的问题,但我不知道如何纠正它。非常感谢任何建议。

1 个答案:

答案 0 :(得分:1)

我怀疑这个问题与如何将比例填充应用于两个比例有关。我不太了解工作原理,无法知道这是错误、有意还是不可避免。可以通过明确关系来解决。

df$y2_trans <- (df$y2 - 280) * 1.0   # 1.0 included here and below in case you want to adjust

# plot 
ggplot (data = df, aes(x = x)) +
  geom_point(aes(x, y)) +
  geom_line(aes(x = x, y = y2_trans), color = "red") +
  geom_point(aes(x = x, y = y2_trans), color = "red") +
  scale_y_continuous(sec.axis = sec_axis(~ (. / 1.0) + 280, 
                                         breaks = 280 + 5*(0:5)),
                     breaks = 5*(0:5))

enter image description here