Gör din plot interaktiv
plotly är ett populärt paket för att skapa interaktiva plottar i Shiny. Det finns flera andra paket för interaktiva visualiseringar, men vi använder plotly framför allt tack vare funktionen ggplotly(), som konverterar en ggplot2-plot till en interaktiv plot.
Den här övningen är en del av kursen
Fallstudier: Bygg webbapplikationer med Shiny i R
Övningsinstruktioner
Koden för Shiny-appen från förra övningen är redan given. Din uppgift är att ersätta ggplot2-plotten med en plotly-plot. Mer specifikt:
- Läs in paketet
plotly. - Ersätt plottens utdatafunktion med
plotlyOutput(rad 20). - Ersätt plottens renderfunktion med
renderPlotly(rad 29). - Konvertera den befintliga
ggplot2-plotten till enplotly-plot (rad 31).
Interaktiv övning med praktiskt arbete
Testa den här övningen genom att slutföra den här exempelkoden.
# 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)