我正在尝试绘制一个连续变量(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级别。 how the shinyApp is now
答案 0 :(得分:1)
当您尝试过滤数据时(好像您从dataf
开始的注释行)似乎已经设置好了。您需要获取filter()
才能识别出您希望它使用input$z
表示的列,而不是使用实际值input$z
(即"cut"
)。如果您更新renderPlot
以便对数据进行这样的过滤
data <-
select(diamonds, input$x, input$y, input$z) %>%
filter(!!(as.name(input$z)) %in% input$show_levels)
然后,该应用程序将按预期运行。 This answer详细说明了为什么/如何处理将闪亮的输入传递给dplyr函数。