繁体   English   中英

如何将自动绘图中呈现的两个图中的线系列组合成一个 plot,共享相同的 y 轴和两个不同的 x 轴?

[英]How to combine the line series in two plots rendered in autoplot into a single plot, sharing the same y-axis and with two different x-axes?

在下面的代码中,我使用autoplot() function 渲染了两个单独的图。第一个 plot ( transPlot1 ) 允许用户通过 slider 输入转换数据系列,而第二个 plot 显示原始未转换系列 ( transPlot2 ) 并且完全static。我想在同一个 plot 中显示两个数据系列,第一个系列显示在主 x 轴上(在左侧,其 x 轴值根据 slider 输入而变化)和第二个系列显示在次要 x 轴上(在右侧,它始终保持固定,因为它显示了转换前的原始数据)。 我想将这两个系列放在同一个 plot 上,这样用户就可以看到数据形状转换的效果。 这是在 XLS 中很容易做到的事情,但我已经迁移到 R。

有关如何执行此操作的任何建议?

代码:

library(feasts)
library(fabletools)
library(ggplot2)
library(shiny)
library(tsibble)

DF <- data.frame(
  Month = c(1:12),
  StateX = c(59,77,45,42,32,26,27,21,19,22,24,10)
)
DF1 <- DF %>% as_tsibble(index = Month)

library(shiny)
ui <- fluidPage(
  sliderInput("lambda","Transformation lambda:",min=-2,max=2,value=0.5,step = 0.1),
  plotOutput("transPlot1"),
  plotOutput("transPlot2"),
)
server <- function(input, output) {
  
  output$transPlot1 <- renderPlot({
    DF1 %>%
      autoplot(box_cox(StateX, input$lambda)) +
      labs(y = "",
           title = latex2exp::TeX(paste0(
             "Transformed units reaching StateX",
             round(input$lambda,2))))
  })
  
  output$transPlot2 <- renderPlot({
    autoplot(DF1, StateX) +
      labs(y = "")
  })  
}
shinyApp(ui, server)

实现所需结果的一种选择是通过autoplot将未转换的系列添加到自动geom_line并添加辅助比例。 像往常一样,在向ggplot添加辅助刻度时,这需要对要显示在辅助轴上的数据进行一些转换。 为此,我添加了一个反应来完成所有的转换,包括 Box-Cox 转换和二级尺度所需的转换。 对于最后一部分,我使用scales::rescale

library(feasts)
#> Loading required package: fabletools
library(fabletools)
library(ggplot2)
library(shiny)
library(tsibble)
library(dplyr)
library(scales)

DF <- data.frame(
  Month = c(1:12),
  StateX = c(59, 77, 45, 42, 32, 26, 27, 21, 19, 22, 24, 10)
)
DF1 <- DF %>% as_tsibble(index = Month)

library(shiny)
ui <- fluidPage(
  sliderInput("lambda", "Transformation lambda:", min = -2, max = 2, value = 0.5, step = 0.1),
  plotOutput("transPlot1")
)
server <- function(input, output) {
  DF1_trans <- reactive({
    DF1 %>%
      mutate(
        state_x_box = box_cox(StateX, input$lambda),
        state_x_raw = scales::rescale(StateX, to = range(state_x_box))
      )
  })
  
  output$transPlot1 <- renderPlot({
    to_range <- range(DF1_trans()$StateX)

    DF1_trans() %>%
      autoplot(state_x_box) +
      geom_line(data = DF1_trans(), aes(Month, state_x_raw, color = "Untransformed Series")) +
      scale_y_continuous(
        sec.axis = sec_axis(
          name = "Untransformed",
          trans = ~ scales::rescale(.x, to = to_range))) +
      labs(
        y = "",
        title = latex2exp::TeX(paste0(
          "Transformed units reaching StateX",
          round(input$lambda, 2)
        ))
      )
  })
}
shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:3492

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM