代码之家  ›  专栏  ›  技术社区  ›  tassones

ggplot2:设置辅助y轴比例

  •  0
  • tassones  · 技术社区  · 3 年前

    有没有办法在中设置辅助y轴的比例 ggplot2 ?在我下面的例子中,辅助y轴是大气压,我想将此辅助y轴刻度的下限设置为900,而不是零。有办法做到这一点吗?

    附言:我认识到 frown upon the use of secondary y-axes 。

    library(ggplot2)
    #> Warning: package 'ggplot2' was built under R version 4.2.3
    
    zz <- data.frame(
      datetime = seq.POSIXt(as.POSIXct('2022-05-07 00:00:00'),
                            as.POSIXct('2022-05-08 23:00:00'),
                            '1 hour'),
      windgust_ms = c(5.0, 5.1, 2.7, 9.4, 7.6, 6.7, 3.0, 7.7, 11.4, 8.2, 7.4, 6.3, 4.4, 3.6, 2.2, 2.9, 4.6, 5.2, 5.0, 3.0, 2.7, 7.1, 10.0, 12.7, 17.5, 17.2, 16.1, 17.0, 18.8, 19.6, 20.6, 19.3, 17.1, 19.9, 16.4, 18.3, 18.3, 15.3, 13.5, 13.8, 13.8, 16.3, 13.3, 12.2, 10.1, 10.1, 13.9, 12.5),
      press_mb = c(1003.5, 1004.0, 1002.5, 1001.6, 1001.4, 999.3, 998.8, 998.4, 998.5, 998.7, 998.4, 998.9, 999.1, 999.7, 999.9, 1000.1, 1000.5, 1000.5, 1000.9, 1001.3, 1001.5, 1002.3, 1002.8, 1003.4, 1004.2, 1005.2, 1005.9, 1006.2, 1006.5, 1006.5, 1006.6, 1006.8, 1007.3, 1007.7, 1008.3, 1009.3, 1010.6, 1011.8, 1012.6, 1013.3, 1013.6, 1013.7, 1014.5, 1015.2, 1015.4, 1015.7, 1016.2, 1016.9))
    
    
    ggplot(zz, aes(x = datetime)) +
      geom_line(aes(y = windgust_ms), color = "blue", linewidth = 1) +
      geom_line(aes(y = press_mb / 50), color = "red", linewidth = 1) +
      scale_y_continuous(
        name = "Wind Gust (m/s)",
        breaks = seq(0, 22, 2),
        limits = c(0, 22),
        expand = c(0, 0),
        sec.axis = sec_axis(trans = ~ . * 50, name = "Barometric Pressure (mb)")) +
      labs(x = NULL,
        y = "Wind Gust (m/s)") +
      theme_minimal()
    

    创建于2023-08-14 reprex v2.0.2

    1 回复  |  直到 3 年前
        1
  •  1
  •   stefan    3 年前

    这当然可以实现。这只是我使用的数据的适当重新缩放问题 scales::rescale :

    library(ggplot2)
    
    zz$press_mb <- scales::rescale(zz$press_mb, from = c(900, 1100), to = c(0, 22))
    
    ggplot(zz, aes(x = datetime)) +
      geom_line(aes(y = windgust_ms), color = "blue", linewidth = 1) +
      geom_line(aes(y = press_mb), color = "red", linewidth = 1) +
      scale_y_continuous(
        name = "Wind Gust (m/s)",
        breaks = seq(0, 22, 2),
        limits = c(0, 22),
        expand = c(0, 0),
        sec.axis = sec_axis(
          trans = ~ scales::rescale(.x, from = c(0, 22), to = c(900, 1100)),
          name = "Barometric Pressure (mb)"
        )
      ) +
      labs(
        x = NULL,
        y = "Wind Gust (m/s)"
      ) +
      theme_minimal()
    

    enter image description here

    推荐文章