为图形添加颜色:单选按钮
当您希望给用户提供多个选项并让其选择其一时,可以使用单选按钮。它们有一个 choices 参数,用于定义用户可以选择的不同选项;还有一个 selected 参数,用于定义初始选中的选项。请注意,没有 value 参数,不过您可以将 selected 理解为发挥了类似的作用。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
已提供上一练习中的 Shiny 应用代码。您的任务是添加单选按钮,让用户可以为图形选择颜色。具体要求:
- 在 UI 中添加 ID 为 "color"、标签为 "Point color" 的单选按钮,并包含 4 个选项:"blue"、"red"、"green"、"black"。
- 在服务器端添加代码,使图中的点使用单选按钮中选定的颜色(第 22 行)。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define UI for the application
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),
# Add radio buttons for colour
___("color", ___, ___)
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
p <- ggplot(gapminder, aes(gdpPercap, lifeExp)) +
# Use the value of the color input as the point colour
geom_point(size = input$size, col = input$___) +
scale_x_log10() +
ggtitle(input$title)
if (input$fit) {
p <- p + geom_smooth(method = "lm")
}
p
})
}
# Run the application
shinyApp(ui = ui, server = server)