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

如何在Plotly(R)瀑布图中设置增减趋势统一图例?

解决方案

要实现单图例带标题、分别展示红色增长和绿色下降的效果,需要对原代码做以下关键调整:

  1. 关闭所有子图的独立图例
  2. 添加虚拟 trace 生成独立的图例项
  3. 配置图例标题

修改后的完整代码

percent <- function(x, digits = 2, format = "f", ...) {
  paste0(formatC(x, format = format, digits = digits, ...), "%")
}

my_plot <- . %>% 
  plot_ly(x = ~Date, y = ~Percent_change, type = "waterfall",
          hoverinfo = "text",
          hovertext = ~paste("Date :", Date,
                             "<br> % Change:", percent(Percent_change)),
          increasing = list(marker = list(color = "red")),
          decreasing = list(marker = list(color = "green")),
          totals = list(marker = list(color = "blue")),
          textposition = "outside") %>%
  add_annotations(
    text = ~unique(Toys),
    x = 0.5,
    y = 1,
    yref = "paper",
    xref = "paper",
    xanchor = "middle",
    yanchor = "top",
    showarrow = FALSE,
    font = list(size = 15),
    yshift = 10
  )  %>%
  layout(yaxis = list(title = "% Change",
                      ticksuffix = "%"),
         xaxis = list(title = "Date"),
         showlegend = FALSE) # 关闭子图自身的图例

# 生成子图并添加自定义图例
final_plot <- example_data %>%
  dplyr::filter(!is.na(Date)) %>% 
  group_by(Toys) %>%
  distinct()  %>%
  do(p = my_plot(.)) %>%
  subplot(nrows = 3, shareX = FALSE, titleY= TRUE, titleX= FALSE) %>%
  # 添加虚拟trace生成图例项(透明不显示在图上)
  add_trace(x = ~Date[1], y = ~Percent_change[1], type = "scatter", mode = "markers",
            marker = list(color = "red"), name = "增长", showlegend = TRUE,
            opacity = 0) %>% # 设为透明,不影响图表显示
  add_trace(x = ~Date[1], y = ~Percent_change[1], type = "scatter", mode = "markers",
            marker = list(color = "green"), name = "下降", showlegend = TRUE,
            opacity = 0) %>%
  # 配置图例标题和样式
  layout(legend = list(title = list(text = "Trend"),
                       orientation = "h", # 可选:横向排列图例
                       x = 0.5, xanchor = "middle")) # 可选:居中显示图例

final_plot

关键改动说明

  • 关闭子图图例:在my_plot的layout中设置showlegend = FALSE,避免每个子图都显示重复图例
  • 添加虚拟trace:通过两个透明的散点图trace,分别对应增长(红色)和下降(绿色)的颜色,仅用于生成独立的图例项,opacity = 0确保它们不会在图表中显示
  • 设置图例标题:在layout的legend参数中添加title = list(text = "Trend"),同时可以按需调整图例的排列方向和位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:15:25