MulaiMulai sekarang secara gratis

Buat plot Anda interaktif

plotly adalah paket populer untuk membuat plot interaktif di Shiny. Ada beberapa paket lain untuk visualisasi interaktif, tetapi kita akan menggunakan plotly terutama karena fungsinya ggplotly(), yang mengonversi plot ggplot2 menjadi plot interaktif.

Latihan ini adalah bagian dari kursus

Studi Kasus: Membangun Aplikasi Web dengan Shiny di R

Lihat Kursus

Petunjuk latihan

Kode untuk aplikasi Shiny dari latihan sebelumnya telah disediakan. Tugas Anda adalah mengganti plot ggplot2 dengan plot plotly. Secara spesifik:

  • Muat paket plotly.
  • Ganti fungsi keluaran plot dengan plotlyOutput (baris 20).
  • Ganti fungsi render plot dengan renderPlotly (baris 29).
  • Konversi plot ggplot2 yang ada menjadi plot plotly (baris 31).

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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)
Edit dan Jalankan Kode