開始使用免費開始

讓你的圖表可互動

plotly 是在 Shiny 中建立互動式圖表的常用套件。還有其他套件能做互動式視覺化,不過我們主要使用 plotly,因為它的 ggplotly() 函式可以把 ggplot2 的圖轉成可互動的版本。

本練習屬於課程

案例研究:使用 R 的 Shiny 建置網頁應用程式

檢視課程

練習說明

這裡提供上一個練習的 Shiny 應用程式碼。你的任務是把 ggplot2 的圖換成 plotly 圖。具體來說:

  • 載入 plotly 套件。
  • 將圖表輸出函式替換為 plotlyOutput(第 20 行)。
  • 將圖表繪製(render)函式替換為 renderPlotly(第 29 行)。
  • 把現有的 ggplot2 圖轉換為 plotly 圖(第 31 行)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Load the plotly package
___

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("title", "Title", "GDP vs life exp"),
      numericInput("size", "Point size", 1, 1),
      checkboxInput("fit", "Add line of best fit", FALSE),
      colourInput("color", "Point color", value = "blue"),
      selectInput("continents", "Continents",
                  choices = levels(gapminder$continent),
                  multiple = TRUE,
                  selected = "Europe"),
      sliderInput("years", "Years",
                  min(gapminder$year), max(gapminder$year),
                  value = c(1977, 2002))
    ),
    mainPanel(
      # Replace the `plotOutput()` with the plotly version
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  # Replace the `renderPlot()` with the plotly version
  output$plot <- renderPlot({
    # Convert the existing ggplot2 to a plotly plot
    ___({
      data <- subset(gapminder,
                     continent %in% input$continents &
                       year >= input$years[1] & year <= input$years[2])
      
      p <- ggplot(data, aes(gdpPercap, lifeExp)) +
        geom_point(size = input$size, col = input$color) +
        scale_x_log10() +
        ggtitle(input$title)
      
      if (input$fit) {
        p <- p + geom_smooth(method = "lm")
      }
      p
    })
  })
}

shinyApp(ui = ui, server = server)
編輯並執行程式碼