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

在R Plotly中绘制多分类变量:两地温度对比图实现问题

解决Plotly合并两个地点温度对比图的问题

问题核心是你错误使用了split参数,导致生成额外异常轨迹,同时未为两个地点指定独立颜色体系。下面是修正后的完整方案:

步骤1:数据读取与预处理

先确保数据读取正确,将date列转为日期格式:

library(plotly)
library(readr)

# 读取数据(替换为你本地的读取方式,比如从Google Sheets导出后读取)
temp_c <- read_csv("your_data_file.csv")
temp_c$date <- as.Date(temp_c$date)

步骤2:创建合并对比图

基于完整数据集,分别为两个地点添加温度范围填充和平均线,避免错误的split参数:

# 初始化图表
fig <- plot_ly()

# 添加Finley的温度范围(max到min填充)和平均线
fig <- fig %>% add_trace(
  data = temp_c[temp_c$location == "finley", ],
  x = ~date, y = ~max_temp_c,
  type = 'scatter', mode = 'lines',
  line = list(color = 'transparent'),
  showlegend = FALSE, name = 'Finley Max'
) %>% add_trace(
  data = temp_c[temp_c$location == "finley", ],
  x = ~date, y = ~min_temp_c,
  type = 'scatter', mode = 'lines',
  fill = 'tonexty', fillcolor = 'rgba(0,100,80,0.2)',
  line = list(color = 'transparent'),
  showlegend = FALSE, name = 'Finley Min'
) %>% add_trace(
  data = temp_c[temp_c$location == "finley", ],
  x = ~date, y = ~ave_temp_c,
  type = 'scatter', mode = 'lines',
  line = list(color = 'green'),
  name = 'Finley 平均温度'
)

# 添加Turnbull的温度范围和平均线(用蓝色系区分)
fig <- fig %>% add_trace(
  data = temp_c[temp_c$location == "turnbull", ],
  x = ~date, y = ~max_temp_c,
  type = 'scatter', mode = 'lines',
  line = list(color = 'transparent'),
  showlegend = FALSE, name = 'Turnbull Max'
) %>% add_trace(
  data = temp_c[temp_c$location == "turnbull", ],
  x = ~date, y = ~min_temp_c,
  type = 'scatter', mode = 'lines',
  fill = 'tonexty', fillcolor = 'rgba(80,100,200,0.2)',
  line = list(color = 'transparent'),
  showlegend = FALSE, name = 'Turnbull Min'
) %>% add_trace(
  data = temp_c[temp_c$location == "turnbull", ],
  x = ~date, y = ~ave_temp_c,
  type = 'scatter', mode = 'lines',
  line = list(color = 'blue'),
  name = 'Turnbull 平均温度'
)

# 调整布局
fig <- fig %>% layout(
  title = "Finley与Turnbull NWR历史温度对比(最高/最低/平均)",
  paper_bgcolor = 'rgb(255,255,255)', plot_bgcolor = 'rgb(229,229,229)',
  xaxis = list(
    title = "日期",
    gridcolor = 'rgb(255,255,255)',
    showgrid = TRUE,
    showline = FALSE,
    showticklabels = TRUE,
    tickcolor = 'rgb(127,127,127)',
    ticks = 'outside',
    zeroline = FALSE
  ),
  yaxis = list(
    title = "温度(摄氏度)",
    gridcolor = 'rgb(255,255,255)',
    showgrid = TRUE,
    showline = FALSE,
    showticklabels = TRUE,
    tickcolor = 'rgb(127,127,127)',
    ticks = 'outside',
    zeroline = FALSE
  )
)

fig

关键修正点

  • 移除了错误的split = c("finley")参数:split是按数据列分组生成轨迹的,传入固定字符串会导致Plotly生成额外无效轨迹,这就是你看到异常第三线的原因。
  • 为两个地点指定独立颜色体系:Finley用绿色系,Turnbull用蓝色系,确保视觉区分清晰。
  • 每个地点的温度范围填充绑定到各自的max和min轨迹,避免交叉填充。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:40:42