Сделайте график интерактивным
plotly — популярный пакет для создания интерактивных графиков в Shiny. Существуют и другие пакеты для интерактивной визуализации, однако мы будем использовать именно plotly — во многом благодаря функции ggplotly(), которая преобразует график ggplot2 в интерактивный.
Это упражнение является частью курса
Примеры использования: создание веб-приложений с Shiny в R
Инструкции к упражнению
Код приложения Shiny из предыдущего упражнения уже подготовлен. Ваша задача — заменить график ggplot2 на график plotly. Для этого:
- Загрузите пакет
plotly. - Замените функцию вывода графика на
plotlyOutput(строка 20). - Замените функцию отрисовки графика на
renderPlotly(строка 29). - Преобразуйте существующий график
ggplot2в графикplotly(строка 31).
Интерактивное практическое упражнение
Попробуйте выполнить это упражнение, дополнив этот пример кода.
# 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)