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

在R语言Plotly中为散点图按指标设置指定颜色

解决方案

我帮你完善了Plotly散点图的代码,实现了CYI指标设为绿色、LYI指标设为红色的需求,同时保留了你设置的悬停文本功能。下面是完整的可运行代码:

library(plotly)

dataset <- data.frame(
  SC = c("A","B","C","D"), 
  CYI = c(100,150,180,80), 
  LYI = c(80,120,190,90)
)

# 定义悬停文本
CYI_Text <- paste("Status Category = ", dataset$SC, "<br>", 
                  "Current Year Interaction = ", dataset$CYI, "<br>")
LYI_Text <- paste("Status Category = ", dataset$SC, "<br>", 
                  "Last Year Interaction = ", dataset$LYI, "<br>")

# 创建散点图
g <- plot_ly(dataset) %>%
  # 添加CYI散点,设置为绿色
  add_trace(
    x = ~SC, 
    y = ~CYI, 
    type = "scatter", 
    mode = "markers",
    marker = list(color = "green", size = 12),  # 绿色标记,调整大小增强辨识度
    hovertext = ~CYI_Text,
    name = "Current Year Interaction (CYI)"
  ) %>%
  # 添加LYI散点,设置为红色
  add_trace(
    x = ~SC, 
    y = ~LYI, 
    type = "scatter", 
    mode = "markers",
    marker = list(color = "red", size = 12),  # 红色标记
    hovertext = ~LYI_Text,
    name = "Last Year Interaction (LYI)"
  ) %>%
  # 调整布局,优化图表可读性
  layout(
    title = "Year-over-Year Interaction Comparison",
    xaxis = list(title = "Status Category"),
    yaxis = list(title = "Interaction Value"),
    showlegend = TRUE
  )

# 显示图表
g

关键说明:

  • 用add_trace()分别为两个指标创建独立的散点轨迹,这样可以单独控制每个指标的颜色和样式
  • 通过marker = list(color = "green")和marker = list(color = "red")精准设置对应指标的标记颜色
  • 保留了你定义的悬停文本,通过hovertext参数绑定到对应轨迹,鼠标悬停时能显示完整信息
  • 添加了布局设置,补充了标题和坐标轴标签,同时开启图例方便区分两个指标

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:34:33