Haz tu gráfica interactiva
plotly es un paquete muy usado para crear gráficas interactivas en Shiny. Hay otros paquetes para visualizaciones interactivas, pero usaremos plotly principalmente por su función ggplotly(), que convierte una gráfica de ggplot2 en una interactiva.
Este ejercicio forma parte del curso
Casos prácticos: crea aplicaciones web con Shiny en R
Instrucciones del ejercicio
Se proporciona el código de la app Shiny del ejercicio anterior. Tu tarea es reemplazar la gráfica de ggplot2 por una de plotly. En concreto:
- Carga el paquete
plotly. - Sustituye la función de salida de la gráfica por
plotlyOutput(línea 20). - Sustituye la función que renderiza la gráfica por
renderPlotly(línea 29). - Convierte la gráfica existente de
ggplot2a una deplotly(línea 31).
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
# 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)