问题是输出对象也在生成所有的网络显示内容。相反,您需要单独提取数据以进行下载。您可以在下载代码中再次调用brushedPoints 来完成此操作。然而,更好的是使用reactive() 函数只执行一次,然后在您需要的任何地方调用它。以下是我将如何修改您的代码以使其正常工作:
data(iris)
ui <- basicPage(
plotOutput("plot1", brush = "plot_brush"),
verbatimTextOutput("info"),mainPanel(downloadButton('downloadData', 'Download'))
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(iris,aes(x=Sepal.Width,y=Sepal.Length)) + geom_point(aes(color=factor(Species))) + theme_bw()
})
selectedData <- reactive({
brushedPoints(iris, input$plot_brush)
})
output$info <- renderPrint({
selectedData()
})
output$downloadData <- downloadHandler(
filename = function() {
paste('SelectedRows', '.csv', sep='') },
content = function(file) {
write.csv(selectedData(), file)
}
)
}
shinyApp(ui, server)
(注意,使用ggplot2,您不需要在brushedPoints 中显式设置xvar 和yvar。因此,我在此处将其删除以增加代码的灵活性。)
我不知道shiny 有任何“套索”风格的免费绘图功能(不过,给它一个星期——他们不断地添加有趣的工具)。但是,您可以通过允许用户选择多个区域和/或单击单个点来模仿行为。服务器逻辑变得更加混乱,因为您需要将结果存储在 reactiveValues 对象中以便能够重复使用它。我做了类似的事情,允许我在一个图上选择点并在其他图上突出显示/删除它们。这比你在这里需要的更复杂,但下面应该可以工作。您可能想要添加其他按钮/逻辑(例如,“重置”选择),但我相信这应该可行。我确实在绘图中添加了选择的显示,以便您跟踪已选择的内容。
data(iris)
ui <- basicPage(
plotOutput("plot1", brush = "plot_brush", click = "plot_click")
, actionButton("toggle", "Toggle Seletion")
, verbatimTextOutput("info")
, mainPanel(downloadButton('downloadData', 'Download'))
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(withSelected()
, aes(x=Sepal.Width
, y=Sepal.Length
, color=factor(Species)
, shape = Selected)) +
geom_point() +
scale_shape_manual(
values = c("FALSE" = 19
, "TRUE" = 4)
, labels = c("No", "Yes")
, name = "Is Selected?"
) +
theme_bw()
})
# Make a reactive value -- you can set these within other functions
vals <- reactiveValues(
isClicked = rep(FALSE, nrow(iris))
)
# Add a column to the data to ease plotting
# This is really only necessary if you want to show the selected points on the plot
withSelected <- reactive({
data.frame(iris
, Selected = vals$isClicked)
})
# Watch for clicks
observeEvent(input$plot_click, {
res <- nearPoints(withSelected()
, input$plot_click
, allRows = TRUE)
vals$isClicked <-
xor(vals$isClicked
, res$selected_)
})
# Watch for toggle button clicks
observeEvent(input$toggle, {
res <- brushedPoints(withSelected()
, input$plot_brush
, allRows = TRUE)
vals$isClicked <-
xor(vals$isClicked
, res$selected_)
})
# pull the data selection here
selectedData <- reactive({
iris[vals$isClicked, ]
})
output$info <- renderPrint({
selectedData()
})
output$downloadData <- downloadHandler(
filename = function() {
paste('SelectedRows', '.csv', sep='') },
content = function(file) {
write.csv(selectedData(), file)
}
)
}
shinyApp(ui, server)