添加图标题:文本输入
在 Shiny 中,只要用户更改任一输入的值,Shiny 就会立即通过服务器函数的 input 参数将该输入的当前值提供给您。您可以使用 input$<inputId> 获取任意输入的值。
若要为文本输入指定默认的初始值,请使用 value 参数。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
给定的 Shiny 应用绘制 gapminder 数据集中各国的人均 GDP 与预期寿命的关系图。您的任务是添加一个文本输入,让用户可以更改图表标题。具体要求:
- 在 UI 中添加一个 ID 为 "title"、标签为 "Title"、默认值为 "GDP vs life exp" 的文本输入。
- 在服务器代码中,使图表标题始终反映该文本输入的当前值:将标题放入
ggtitle()函数中(第 24 行)。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Load the ggplot2 package for plotting
library(ggplot2)
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
# Add a title text input
___(___, ___, ___)
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
ggplot(gapminder, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10() +
# Use the input value as the plot's title
ggtitle(___)
})
}
# Run the application
shinyApp(ui = ui, server = server)