เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ทำให้พล็อตของคุณโต้ตอบได้

plotly เป็นแพ็กเกจยอดนิยมสำหรับสร้างพล็อตแบบโต้ตอบใน Shiny มีแพ็กเกจอื่นสำหรับการแสดงผลแบบโต้ตอบอีกหลายตัว แต่เราจะใช้ plotly เป็นหลัก เนื่องจากมีฟังก์ชัน ggplotly() ที่แปลงพล็อตจาก ggplot2 ให้กลายเป็นพล็อตแบบโต้ตอบได้

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

ดูคอร์ส

คำแนะนำการฝึกหัด

โค้ด Shiny app จากแบบฝึกหัดที่แล้วได้ถูกเตรียมไว้ให้แล้ว ให้แทนที่พล็อตแบบ 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)
แก้ไขและรันโค้ด