使用 ggplot2 反转次要 y 轴图

Reverse secondary y-axis plot with ggplot2

我尝试在堆栈溢出中搜索答案,但我找不到。

我正在使用一个反转的 y 轴来绘制一个 y 变量随时间的变化,我希望以正常顺序(而不是反转)获得我的次要 y 轴。

library(tidyverse)
library(scales)
library(lemon)

    base_nivelprecip %>%
      mutate(nivel = as.double(nivel),
             precip = as.double(precip)) %>% 
      mutate(precip_rescaled = precip/200) %>% 
      ggplot(aes(x = data, y = nivel,
                 xmin = as.POSIXct("2012-05-01", "%Y-%m-%d"), 
                 xmax = as.POSIXct("2020-04-30",  "%Y-%m-%d"))) + 
    
      geom_col(aes(x = data, y = precip_rescaled), fill = '#8D8DAA', size = 3) +
      geom_line(group = 1, color = '#041562', size = 0.3) +
      labs(x = "", y = "Groundwater level (m)") +
      scale_y_reverse(limits = c(5,-0.5) ,  sec.axis = sec_axis(~rev(.)*200, name = "Precipitation (mm)")) +
      lemon::facet_rep_wrap(~poco, nrow = 3, repeat.tick.labels = TRUE) +
      theme_bw() +
      theme(text=element_text(size=12),
            axis.text.x = element_text(size = 8)

虽然我尝试了一些转换,但我能得到的最好的是:

但我希望 geom_col(在辅助轴中)从辅助轴 0 开始,而不是在主轴上。有人可以帮我吗?谢谢。我的数据样本在这里:https://docs.google.com/spreadsheets/d/1xgj3Gan1Lj9qO2aEGdLpiUOBk9g8USMS/edit?usp=sharing&ouid=111814647952336460862&rtpof=true&sd=true

请记住,在 ggplot2 中,辅助轴是一种装饰,不会改变数据的映射。因此,如果您希望将数据映射到次轴,则需要将其转换为出现在主轴上您想要的位置(这不像 Excel 那样会自动发生)。然后还需要定义副轴的变换。

在下面的例子中,我有一个反转的主轴,它决定了点的位置。我还有一个辅助轴,可将主轴转换为相反的斜率。此处,~35-. 表示“进行变换,使输入 0 的值变为 35,并且斜率反转。”

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  scale_y_continuous(trans = "reverse",
    sec.axis = sec_axis(~35-., name = "how far below 35 mpg"))

也许实现此目的的最简单方法是以与伪造次轴相同的方式“伪造”主轴。这样,您就不需要 scale_y_reverse:

的额外复杂化
library(tidyverse)
library(scales)
library(lemon)

base_nivelprecip %>%
  mutate(nivel = as.double(nivel),
         precip = as.double(precip),
         data = as.POSIXct(data, format = "%m/%d/%Y")) %>% 
  mutate(precip_rescaled = precip/200 ,
         nivel_rescaled = -nivel + 2.5) %>% 
  ggplot(aes(x = data, y = nivel_rescaled,
             xmin = as.POSIXct("2012-05-01", "%Y-%m-%d"), 
             xmax = as.POSIXct("2020-04-30",  "%Y-%m-%d"))) +

  geom_col(aes(x = data, y = precip_rescaled), 
           colour = '#8D8DAA', size = 1) +
  geom_line(color = '#041562', size = 0.3) +
  labs(x = "", y = "Groundwater level (m)") +
  scale_y_continuous(labels = function(x) -(x - 2.5), limits = c(0, 2.5),
                  sec.axis = sec_axis(~.*200, 
                                      name = "Precipitation (mm)")) +
  lemon::facet_rep_wrap(~poco, nrow = 3, repeat.tick.labels = TRUE) +
  theme_bw() +
  theme(text=element_text(size=12),
        axis.text.x = element_text(size = 8))