CommencerCommencer gratuitement

Rendez votre graphique interactif

plotly est un package populaire pour créer des graphiques interactifs dans Shiny. Il existe plusieurs autres packages pour les visualisations interactives, mais nous utiliserons principalement plotly grâce à sa fonction ggplotly(), qui convertit un graphique ggplot2 en graphique interactif.

Cet exercice fait partie du cours

Études de cas : créer des applications web avec Shiny en R

Afficher le cours

Instructions

Le code de l’application Shiny de l’exercice précédent est fourni. Votre tâche est de remplacer le graphique ggplot2 par un graphique plotly. Plus précisément :

  • Chargez le package plotly.
  • Remplacez la fonction d’affichage du graphique par plotlyOutput (ligne 20).
  • Remplacez la fonction de rendu du graphique par renderPlotly (ligne 29).
  • Convertissez le graphique ggplot2 existant en graphique plotly (ligne 31).

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# 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)
Modifier et exécuter le code