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

ggplot2设置的scale_fill_manual标签转plotly后失效如何解决

问题原因与解决方法

ggplotly()的转换逻辑无法自动识别scale_fill_manual()中配置的labels参数,只会读取映射字段的原始因子值,所以会出现自定义标签丢失、还原为-1/1原始值的问题,并非plotly不支持自定义图例标签。

解决方法1:提前定义因子标签(推荐)

直接在数据映射阶段给因子设置自定义标签,不需要在scale中单独配置labels,ggplot和ggplotly都能正常识别:

library(ggplot2)
library(plotly)

dt <- structure(list(date = structure(c(18651L, 18658L, 18665L, 18672L, 
18679L, 18686L, 18693L, 18700L, 18707L, 18714L), class = c("IDate", 
"Date")), churn = c(-3.27088948787062, -0.582518144525087, -0.125024925224327, 
-0.333746898263027, -0.685714285714286, -0.340165549862042, 0.0601176470588235, 
-0.119351608461635, -0.0132513279284316, -0.011201854099989)), row.names = c(NA, 
-10L), class = c("data.table", "data.frame"))

plot_ggplot <- ggplot(dt, aes(x = date, y = churn * 100)) +
  geom_bar(stat = "identity", aes(fill = factor(sign(churn), levels = c(-1, 1), labels = c("Growing base", "Declining base")))) +
  scale_fill_manual(
    values = c("#4da63f", "#e84e62")
  ) +
  ylim(-75, 25) +
  labs(
    title = "Weekly churn rate",
    fill = "Legend"
  )

plot_ggplotly <- ggplotly(plot_ggplot)
plot_ggplotly

解决方法2:手动修改plotly对象属性

如果不想改动原有ggplot代码,可以在生成ggplotly对象后手动修改图例名称:

# 沿用原有代码生成的plot_ggplot对象
plot_ggplotly <- ggplotly(plot_ggplot)
# 手动修改两个系列的图例名称
plot_ggplotly$x$data[[1]]$name <- "Growing base"
plot_ggplotly$x$data[[2]]$name <- "Declining base"
# 输出查看效果
plot_ggplotly

两种方案都可以正常实现自定义图例标签的需求,方法1通用性更强,无需针对plotly做额外适配。

内容的提问来源于stack exchange,提问作者Merijn van Tilborg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:45:06