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

R语言Plotly自定义柱状图:移除折线、加均值线与配置图例

Plotly R 分组柱状图自定义调整实现

核心修改逻辑

  • 移除cost对应的红色折线:将cost对应绘图trace的线条设置为完全透明(线宽为0),仅保留图例映射项,原有的黑边白底数值标注逻辑完全保留
  • 新增share变量均值水平参考线:提前计算share列平均值,通过add_hline()添加Y轴方向水平参考线,设置为辨识度高的虚线样式

修改后完整可运行代码

df <- data.frame (model  = c("A", "B", "C","D","E","F"),
                  share = c(12,20,15,9,60,20),
                  sale = c(16,25,18,14,67,28),
                  cost = c(14,19,28,24,57,28))

# 按cost降序设置model因子水平
df$model <- factor(df$model, levels = arrange(df, desc(df$cost))$model)

library(tidyverse)
library(plotly)

df_long <- df %>% 
  pivot_longer(
    cols = -model
  ) 

# 提前计算share变量平均值
share_avg <- mean(df$share)

df_long %>% 
  filter(name != "cost") %>% 
  plot_ly(x = ~model, y = ~value, color = ~name, type = "bar", 
          customdata = ~name,  colors = c("blue", "gray"),
          hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>",
                                 "Name: %{customdata}<extra></extra>")) %>%
  # 保留cost图例项,设置线条完全透明不显示
  add_lines(inherit = F, data = df, x = ~model, 
            y = ~cost, color = I("red"),
            name = "cost",
            line = list(width = 0, color = "rgba(0,0,0,0)"),
            hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>",
                                   "Name: cost<extra></extra>")) %>% 
  # 保留黑边白底cost数值标注
  add_annotations(data = df, x = ~model, y = ~cost, text = ~cost,
                  bgcolor = "white", bordercolor = "black", 
                  xshift = 15, yshift = 15, showarrow = F) %>%
  # 添加share均值水平参考线
  add_hline(y = share_avg, line = list(dash = "dash", color = "darkorange"),
            name = paste0("share均值: ", round(share_avg,2)),
            hovertemplate = "share平均值: %{y}<extra></extra>") %>%
  layout(barmode = "group")

效果说明

  • 图例中会同时显示sale、share柱形项和cost项,图面无红色cost折线,仅保留每个model对应cost的黑边白底色数值框
  • 图中会显示橙色虚线水平参考线,对应share变量的平均值位置,悬浮可查看具体数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:51:32