让您的图表可交互
plotly 是在 Shiny 中创建交互式图表的常用包。还有其他用于交互式可视化的包,但我们将使用 plotly,主要是因为它的函数 ggplotly(),可以把 ggplot2 图形转换为交互式图形。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
这里提供了上一个练习中的 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)