绘制数据图
请回忆,图形是输出对象,因此需要通过 plotOutput() + renderPlot() 函数添加到 Shiny 应用中。输出函数添加到 UI,用于确定图形放置位置;服务器端的渲染函数负责生成图形。
您的任务是在应用中添加一幅「人均 GDP」与「预期寿命」的散点图。绘图所用数据应与表格中显示的数据一致;也就是说,图中只应显示与输入筛选条件匹配的记录。renderPlot() 内的代码无法访问 renderTable() 内定义的任何变量,因此您需要直接复制并复用相同的代码。稍后我们会学习如何避免这种重复。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
- 在 UI 中添加一个图形输出的占位符,ID 为 "plot"。
- 在服务器端第 30 行使用合适的渲染函数创建图形。
- 在第 32 行复用输出表格所用的相同数据筛选代码来生成绘图数据。
交互式实操练习
通过完成这段示例代码来试试这个练习。
ui <- fluidPage(
h1("Gapminder"),
sliderInput(inputId = "life", label = "Life expectancy",
min = 0, max = 120,
value = c(30, 50)),
selectInput("continent", "Continent",
choices = c("All", levels(gapminder$continent))),
# Add a plot output
___(___),
tableOutput("table")
)
server <- function(input, output) {
output$table <- renderTable({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
# Create the plot render function
output$plot <- ___({
# Use the same filtered data code that the table uses
data <- ___
___
___
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)