You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Shiny图形选择实现tweets数据子集展示的技术问询

实现框选地图筛选对应城市推文的方案

没问题,我帮你调整代码实现这个功能。核心是先把框选区域对应的州名提取出来,再匹配到tweets数据里的城市,最后展示筛选后的结果。以下是修改后的完整代码,后面我会拆解关键改动点:

library(shiny)
library(rhandsontable)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(twitteR)
setwd("C:/Users/Marc/Dropbox/PROJECTEN/Lopend/bank_mining/test_data")
source("functions.R")
tweets <- data.frame(
  city = c("New york", "Texas"),
  tweet = c("Test1", "Test"),
  stringsAsFactors = FALSE  # 确保字符列不转成因子,方便后续匹配
)

# 统一州名格式:把tweets的city转成小写,和地图数据的region格式对齐
tweets$state <- tolower(tweets$city)

shinyApp(
  ui = dashboardPage(
    dashboardHeader(
      title = "Tweetminer", titleWidth = 350
    ),
    dashboardSidebar(
      width = 350,
      sidebarMenu(
        menuItem("Menu Item")
      )
    ),
    dashboardBody(
      fluidRow(
        tabBox(
          tabPanel("Set tweets2", 
                   plotOutput('plot', brush = brushOpts(id = "plot1_brush")),
                   h4("Brushed states"), verbatimTextOutput("selected_states"),
                   h4("Filtered tweets"), dataTableOutput("filtered_tweets")  # 新增展示筛选后推文的组件
          )
        )
      )
    )
  ),
  server = function(input, output) {
    # 先定义地图数据的反应式对象,方便重复使用
    all_states <- reactive({
      map_data("state")
    })
    
    output$plot <- renderPlot({
      states_positive <-c("new york")
      states_negative <- c("texas")
      
      ggplot(all_states(), aes(x=long, y=lat, group = group)) +
        geom_polygon(fill="grey", colour = "white") +
        geom_polygon(fill="green", data = filter(all_states(), region %in% states_positive)) +
        geom_polygon(fill="red", data = filter(all_states(), region %in% states_negative))
    })
    
    # 提取框选的州名
    selected_states <- reactive({
      req(input$plot1_brush)  # 等待brush输入
      brushed_points <- brushedPoints(all_states(), input$plot1_brush)
      # 提取唯一的州名(因为框选一个州会有很多点)
      unique(brushed_points$region)
    })
    
    # 展示选中的州名
    output$selected_states <- renderPrint({
      selected_states()
    })
    
    # 筛选并展示对应推文
    output$filtered_tweets <- renderDataTable({
      req(selected_states())  # 等待选中的州数据
      # 匹配选中的州和tweets里的state列
      tweets %>% filter(state %in% selected_states()) %>% select(city, tweet)  # 只展示需要的列
    })
  }
)

关键改动说明:

  • 统一格式:给tweets新增了state列,转成小写,和all_states里的region(小写州名)格式对齐,避免大小写匹配问题。
  • 反应式变量selected_states:从框选的点中提取唯一的州名,确保即使框选一个州的多个点,也只会得到一个州名。
  • 新增UI组件:添加了dataTableOutput来展示筛选后的推文,比纯文本更直观;同时保留了selected_states的输出,方便调试查看选中的州。
  • 依赖检查:用req()确保只有当brush输入存在时,才执行后续的筛选和渲染,避免空输入导致的错误。

如果你的实际应用中tweets的城市名格式更复杂(比如包含城市而非州),可以调整state列的生成逻辑,比如用地理编码工具把城市映射到对应的州,但当前示例中我们先基于现有数据的匹配逻辑来实现。

内容的提问来源于stack exchange,提问作者Henk Straten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:39:09