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

R语言Plotly绘图:仅让foo分类在图例中显示的实现方法

R Plotly 仅显示指定分类图例的实现方法

你之前的配置失效原因是:直接通过plot_ly按color = ~Category分组时,会自动为每一类生成独立trace,全局设置showlegend=F会作用于所有trace,需要单独对不需要显示图例的分类配置该参数,以下是两种可行实现方案:

方案1:拆分数据集分别添加trace(直观可控)

library(dplyr)
library(plotly)
library(plyr)

df <- data.frame(
    Category = c('foo', 'bar', 'bar', 'foo'),
    x = c(2.1, 3.4, 4, 4),
    y = c(16, 21, 10, 17)
)

palette <- c("green", "red")

fig <- plot_ly() %>%
  # 添加foo分类trace,显示图例
  add_trace(
    data = filter(df, Category == "foo"),
    x = ~x, y = ~y, size = I(10), color = I("green"),
    symbol = I(15), hoverinfo = 'y', name = "foo", showlegend = TRUE
  ) %>%
  # 添加bar分类trace,隐藏图例
  add_trace(
    data = filter(df, Category == "bar"),
    x = ~x, y = ~y, size = I(10), color = I("red"),
    symbol = I(17), hoverinfo = 'y', name = "bar", showlegend = FALSE
  )

fig

方案2:基于原有代码修改,无需拆分数据集

通过style函数定向修改对应trace的showlegend属性即可,R默认Category因子按字母排序,bar对应第1条trace,foo对应第2条trace:

library(dplyr)
library(plotly)
library(plyr)

df <- data.frame(
    Category = c('foo', 'bar', 'bar', 'foo'),
    x = c(2.1, 3.4, 4, 4),
    y = c(16, 21, 10, 17)
)

palette <- c("green", "red")

fig <- plot_ly(
    data = df, x = ~x, y = ~y, size = 10, color = ~Category, colors = palette,
    symbol = ~Category, hoverinfo = 'y', symbols = c(15, 17)
) %>%
  # 隐藏bar对应trace的图例
  style(showlegend = FALSE, traces = 1)

fig

如果不确定分类对应的trace序号,可以运行plotly_json(fig)查看trace的name属性对应调整traces参数的取值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:15:03