我正在尝试绘制一个连续变量 (y) 与另一个 (x) 的关系,并根据第三个分类变量 (z) 为图中的数据点着色。为了选择这三个变量,我使用了一个 selectInput 函数,但是为了选择我想要绘制的可能的类别(levels(input$z)),我使用了一个 uiOutput 函数。我正在尝试对过滤后的数据框(dataf)中的选定级别进行子集化,但这不起作用。一些反应式表达式正在工作,但我使用子集回滚了代码,因为当我在 renderPlot 函数中使用 ( dataf <- filter(data(), input$z %in% input$show_levels)) 时,我没有得到任何绘制的数据点。
我已经使用 diamonds 数据集准备了我需要的简化版本。例如,我需要我的 shinyApp 来绘制奖品与克拉的关系,点的颜色取决于切割,并且只能表示具有特定切割的点(例如 cut == c("Fair", "Good" ).)
library(shiny)
library(ggplot2)
library(RColorBrewer)
library(dplyr)
cont_vars <- c("price", "carat", "x", "y", "z", "depth", "table")
discr_vars <- c("cut", "color", "clarity")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Analysis of 'diamonds' dataset"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
# Select variable for y-axis
selectInput(inputId = "y",
label = "Y-axis:",
choices = cont_vars,
selected = cont_vars[1]),
# Select variable for x-axis
selectInput(inputId = "x",
label = "X-axis:",
choices = cont_vars,
selected = cont_vars[2]),
# Select variable for color
selectInput(inputId = "z",
label = "Z-axis:",
choices = discr_vars,
selected = discr_vars[1]),
# Select level/s to show for the z category
uiOutput("selected_z")
),
# Show the plot
mainPanel(
plotOutput("scatterplot")
)
)
)
# Define server logic required to draw a scatterplot
server <- function(input, output) {
# Show levels for the discrete variable selected in input$selected_z
output$selected_z <- renderUI({
checkboxGroupInput(inputId = "show_levels",
label = "Select category/ies to represent:",
choices = choices_z(),
selected = choices_z())
})
choices_z <- reactive({
df <- select(diamonds, input$z)
return(levels(df[[1]]))
})
output$scatterplot <- renderPlot({
# generate df based on inputs selected
data <- select(diamonds, input$x, input$y, input$z)
# dataf <- filter(data(), input$z %in% input$show_levels)
ggplot(data, aes_string(x = input$x, y = input$y,
color = input$z)) +
geom_point(size = 4) +
scale_color_brewer(palette = "Paired") +
theme_light()
})
}
# Run the application
shinyApp(ui = ui, server = server)
我希望选择我对 checkboxGroupInput (input$showlevels) 感兴趣的 input$show_levels 分类变量(级别),并仅显示散点图中所选类别中的点。现在我得到了用于显示级别的 checkboxGroupInput 函数(见下图),但恐怕它没有连接到服务器,并且正在绘制 input$z 的所有级别。 现在shinyApp怎么样