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

如何在Shiny缩放后的图表中仅显示可见数据点的标签?

解决Shiny缩放ggplot2图表时仅显示可见数据点标签的问题

问题背景

用ggplot2绘制大型散点图展示元素随运行周数的数值变化,通过ggrepel优化标签显示仍有重叠。尝试用Shiny实现图表缩放功能,但缩放后所有标签持续显示,导致数据点被遮挡,需要实现仅为当前可见区域内的数据点添加标签。

解决方案

核心思路是在渲染缩放后的图表时,先根据当前的缩放范围过滤数据,仅为落在可见区域内的数据点生成标签。修改后的完整代码如下:

library(shiny)
library(ggplot2)
library(ggrepel)
library(dplyr)

ui <- fluidPage(
  fluidRow(
    column(width = 6, class = "well",
           h4("Zoom here"),
           fluidRow(
             column(width = 6,
                    plotOutput("plot2", height = 500,
                               brush = brushOpts(
                                 id = "plot2_brush",
                                 resetOnNew = TRUE
                               )
                    )
             ),
             column(width = 6,
                    plotOutput("plot3", height = 500)
             )
           )
    )
  )
)

server <- function(input, output) {
  ranges2 <- reactiveValues(x = NULL, y = NULL)

  output$plot2 <- renderPlot({
    tbl2 %>%  
      ggplot(aes(x = Weeks, y = maxOpenings, group = Weeks)) +
      geom_point(color = "pink", size = 2) +
      geom_text_repel(aes(label = Element)) +
      theme_classic()
  })

  output$plot3 <- renderPlot({
    # 根据当前缩放范围过滤数据
    filtered_data <- tbl2
    if (!is.null(ranges2$x) && !is.null(ranges2$y)) {
      filtered_data <- tbl2 %>%
        filter(Weeks >= ranges2$x[1], Weeks <= ranges2$x[2],
               maxOpenings >= ranges2$y[1], maxOpenings <= ranges2$y[2])
    }
    
    tbl2 %>%  
      ggplot(aes(x = Weeks, y = maxOpenings, group = Weeks)) +
      geom_point(color = "pink", size = 2) +
      # 仅为过滤后的数据绘制标签
      geom_text_repel(data = filtered_data, aes(label = Element)) +
      theme_classic() +
      coord_cartesian(xlim = ranges2$x, ylim = ranges2$y, expand = FALSE)
  })

  observe({
    brush <- input$plot2_brush
    if (!is.null(brush)) {
      ranges2$x <- c(brush$xmin, brush$xmax)
      ranges2$y <- c(brush$ymin, brush$ymax)
    } else {
      ranges2$x <- NULL
      ranges2$y <- NULL
    }
  })
}

shinyApp(ui = ui, server = server)

关键修改说明

  • 数据过滤:在渲染右侧缩放图表时,通过filter函数筛选出落在当前x、y缩放范围内的数据行,存储为filtered_data
  • 标签绘制控制:将geom_text_repel的data参数指定为filtered_data,仅为可见区域内的数据点生成标签
  • 兼容未缩放状态:当未进行刷选缩放时(ranges2$x或ranges2$y为NULL),不对数据做过滤,保持原始的全量标签显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 06:17:00