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

如何用R语言Shiny+Plotly实现多选变量累加拼接可视化

实现方案

核心逻辑

  • 借助plotly的subplot()接口实现多图横向拼接,设置nrows = 1保证所有选中变量的图表排在同一行
  • 遍历用户选中的所有数值变量,分别生成带阈值色标的折线图
  • 开启X轴共享、保留各子图独立Y轴标题,通过子图间距自然分隔不同变量的图表

完整可运行代码

library(shiny)
library(plotly)
library(dplyr)

set.seed(123)
df <- data.frame(x = seq.Date(as.Date("2000/1/1"), by = "month", length.out = 100),
                 cat = sample(c("m1","m2","m3"),100, replace = TRUE),
                 a = cumsum(rnorm(100)),
                 b = rnorm(100),
                 c = rnorm(100),
                 d = rnorm(100))

ui <- fluidPage(
  selectInput("x","变量选择",names(df)[-c(1,2)],NULL,multiple = TRUE),
  selectInput("y", "类别筛选", unique(df$cat), NULL, multiple = TRUE),
  numericInput("ls","上限阈值",value = 2, min = -100, max = 100),
  numericInput("li","下限阈值",value = -2, min = -100, max = 100),
  plotlyOutput("plot1")
)

server <- function(input, output, session) { 
  output$plot1 <- renderPlotly({    
    req(input$y, input$x, input$ls, input$li)
    # 过滤基础数据
    filter_df <- df %>% filter(cat %in% input$y)
    
    # 遍历每个选中的变量生成独立绘图对象
    plot_list <- lapply(input$x, function(var) {
      curr_df <- filter_df %>% select(x, all_of(var))
      # 计算阈值颜色
      curr_df$estado <- case_when(
        curr_df[[2]] > input$ls ~ "red",
        curr_df[[2]] < input$li ~ "green",
        .default = "orange"
      )
      # 生成单变量图
      p <- plot_ly(curr_df, x = ~x, y = ~.data[[var]], type = "scatter", mode = "lines") %>%
        add_trace(x = ~x, y = ~.data[[var]], 
                  marker = list(color = ~estado, size = 6, symbol = "square"),
                  showlegend = FALSE) %>%
        layout(
          plot_bgcolor = "#e5ecf6", 
          yaxis = list(title = paste(var,"mg/l")),
          # 只有第一个子图显示X轴标题
          xaxis = list(title = ifelse(var == input$x[1], "日期", ""))
        )
      return(p)
    })
    
    # 横向拼接所有子图
    subplot(plot_list, nrows = 1, shareX = TRUE, titleY = TRUE, margin = 0.05) %>%
      layout(
        title = '污水质量变化趋势',
        legend = list(orientation = 'h')
      )
  })
}

shinyApp(ui, server)

效果说明

选中多个变量后,图表会自动从左到右依次排布,所有子图共享X轴(日期),每个子图有独立的Y轴标题和阈值标记,子图间自带间距分隔,符合需求的拼接效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:45:01