簡體   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