Aan de slagBegin gratis

Maak je plot interactief

plotly is een populair pakket om interactieve plots in Shiny te maken. Er zijn nog andere pakketten voor interactieve visualisaties, maar we gebruiken plotly vooral vanwege de functie ggplotly(), die een ggplot2-plot omzet in een interactieve plot.

Deze oefening maakt deel uit van de cursus

Casestudies: webapplicaties bouwen met Shiny in R

Bekijk cursus

Oefeninstructies

De code voor de Shiny-app uit de vorige oefening is gegeven. Jij vervangt de ggplot2-plot door een plotly-plot. Specifiek:

  • Laad het pakket plotly.
  • Vervang de plot-outputfunctie door plotlyOutput (regel 20).
  • Vervang de plot-renderfunctie door renderPlotly (regel 29).
  • Zet de bestaande ggplot2-plot om naar een plotly-plot (regel 31).

Interactieve oefening met praktijkervaring

Probeer deze oefening door deze voorbeeldcode aan te vullen.

# 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)
Code bewerken en uitvoeren