r - 使用 plotOutput 中的过滤器获取 Shiny 应用程序中的动态用户定义数据
问题描述
我在过滤 ggplot2 可视化数据时遇到了麻烦。我想使用过滤器并输入 f 值,例如使用
data %>%
filter(Col == Number)
ggplot()
根据数据集进行可定制的绘图
我使用此代码生成了一个 Shiny 应用程序,该应用程序能够让用户上传数据并可以交互地绘制它,但过滤器不起作用。
:
library(shiny)
library(tidyverse)
ui <- shinyUI(
fluidPage(
h1(' output'),
h2('Graphics'),
sidebarLayout(
sidebarPanel(
fileInput(inputId = 'file1', label = 'Upload your Data:', accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$hr(),
selectInput('xcol', "X variable:", "", selected = ""),
selectInput('ycol', 'Y variable:', "", selected = ""),
selectInput('filter1', 'Filter:', "", selected = "", multiple = TRUE),
selectInput('filter2', 'Filter Value',"",selected = "")
),
mainPanel(
plotOutput("plot")
)
)
)
)
server <- shinyServer(function(session, input, output){
data <- reactive({
req(input$file1)
inFile <- input$file1
df <- read_csv(inFile$datapath)#, header = T, sep=",")
updateSelectInput(session, inputId = 'xcol', label = 'X variable:',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'ycol', label = 'Y variable:',
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = 'filter1', label = 'Filter:',
choices = names(df), selected ="")
observe({
updateSelectInput(session, inputId = 'filter2', label = 'Filter value', choices =c(0:10))
})
return(df)
})
output$plot <- renderPlot({
F1 <- input$filter1
F2 <- input$filter2
data() %>% filter(F1==F2)%>%
ggplot(aes(x =data()[input$xcol],y= data()[input$ycol]))+
geom_point()
})
})
shinyApp(ui = ui, server = server)
太感谢了
解决方案
ggplot()
就我个人而言,我不会在电话中做任何子集。您也不需要(实际上不应该)data()
在ggplot()
调用中指定。这就是我可能会这样做的方式(尽管如果您不提供可重现的数据则很难测试):
x_var <- reactive(input$xcol)
y_var <- reactive(input$ycol)
data() %>%
filter(F1 == F2) %>%
ggplot(aes_string(x = x_var(), y = y_var())) +
geom_point()
关于我的最后一点,请考虑以下内容之间的区别:
mtcars %>% filter(carb == 2) %>% ggplot(aes(x = carb, y = wt)) + geom_point()
# this works!
mtcars %>% filter(carb == 2) %>% ggplot(aes(x = mtcars$carb, y = mtcars$wt)) + geom_point()
# this doesn't
后者不起作用,因为它试图绘制mtcars$carb
,而不是过滤后的 ( mtcars == 2
) 向量。
推荐阅读
- javascript - 如何在 VueJS 中使用闭包获取汇总数据
- python - 如何使用 pyvmomi 将 ESXi 主机置于维护模式?
- ruby-on-rails - 查看自定义 Rails 生成器中的更改
- c# - 查找形状上的角/边(可以定义该形状的最小顶点)
- angular - 如何通过单击按钮选择使用 Async Pipe 绑定到可观察对象的所有项目 ID?
- python - 为什么我的裁剪图像被保存到不正确的目录?
- ruby-on-rails - 如何在 rails_admin 中使用魔法宝石
- python - Python pyasn1 通过 sqlalchemy 发生冲突
- bash - 程序化 ngrok 隧道 url
- linux - 如何在 Linux 上运行从 Github 下载并解压的本地 python 3.5/3.6 包