如何用e_remove_serie_p单独移除系列而不重绘其他系列?
动态移除/添加echarts4r系列(基于长格式数据)
不用重新渲染整个图表,通过echarts4rProxy结合e_remove_serie_p和e_add_serie_p就能实现动态操作。核心是跟踪选中项的变化,针对取消选中的大洲移除对应系列,新增选中的则添加系列。
关键实现步骤
- 初始渲染时加载所有大洲的数据,确保所有系列都存在于图表中,为后续动态操作提供基础。
- 用
reactiveVal存储上一次选中的大洲列表,对比当前选中项,精准定位需要移除/添加的项。 - 使用系列名称(即大洲名)调用
e_remove_serie_p,比索引更可靠,避免因系列顺序变化导致的错误。 - 新增选中项时,过滤对应大洲的数据,通过
e_add_serie_p动态添加系列。
完整代码
library(shiny) library(echarts4r) library(dplyr) library(gapminder) # Prepare the summarized data gapminder_summary <- gapminder %>% group_by(continent, year) %>% summarize(mean_lifeExp = mean(lifeExp), .groups = 'drop') # Define UI for the application ui <- fluidPage( titlePanel("Mean Life Expectancy by Continent Over Time"), sidebarLayout( sidebarPanel( checkboxGroupInput( inputId = "selected_continents", label = "Select Continents:", choices = unique(gapminder_summary$continent), selected = unique(gapminder_summary$continent) ) ), mainPanel( echarts4rOutput(outputId = "lifeExpPlot"), br(), br() ) ) ) # Define server logic required to draw the plot server <- function(input, output) { # 存储上一次选中的大洲,用于对比变化 prev_selected <- reactiveVal(unique(gapminder_summary$continent)) # 初始渲染所有数据 output$lifeExpPlot <- renderEcharts4r({ gapminder_summary %>% group_by(continent) %>% e_chart(x = year) %>% e_line(mean_lifeExp) %>% e_y_axis( min = min(gapminder_summary$mean_lifeExp), max = max(gapminder_summary$mean_lifeExp) ) %>% e_x_axis( min = min(gapminder_summary$year), max = max(gapminder_summary$year) ) }) observeEvent(input$selected_continents, { current <- input$selected_continents prev <- prev_selected() # 找出需要移除的大洲:之前选中但现在未选中的 to_remove <- setdiff(prev, current) # 找出需要添加的大洲:现在选中但之前未选中的 to_add <- setdiff(current, prev) proxy <- echarts4rProxy("lifeExpPlot") # 移除对应系列 for(continent in to_remove) { proxy <- proxy %>% e_remove_serie_p(serie_name = continent) } # 添加对应系列 for(continent in to_add) { # 过滤当前大洲的数据 data <- gapminder_summary %>% filter(continent == .env$continent) proxy <- proxy %>% e_add_serie_p( name = continent, type = "line", data = data$mean_lifeExp, x_axis_data = data$year ) } # 更新上一次选中的记录 prev_selected(current) }) } # Run the application shinyApp(ui = ui, server = server)
代码说明
prev_selected用于记录上一次的选中状态,通过对比当前状态,精准找到需要操作的系列。e_remove_serie_p直接使用大洲名作为serie_name,避免了索引可能带来的混乱。- 添加系列时,通过
e_add_serie_p传入对应大洲的x轴数据和y轴数据,确保系列正确渲染。
内容的提问来源于stack exchange,提问作者Pascal Schmidt
相关产品推荐
相关产品推荐

