R语言plotly绘制组合图时如何为cost图例项添加黑色边框
问题描述
我有3个数值变量,使用plot_ly绘制组合图:其中sale和share列以分组柱状形式可视化,cost列以红色折线展示。现在需要自定义调整图例,为图例中的cost标识添加黑色边框,效果见预期输出。
初始代码
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) df_long <- df %>% pivot_longer( cols = -model ) 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>")) %>% add_lines(inherit = F, data = df, x = ~model, y = ~cost, color = I("red"), name = "cost", hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>", "Name: cost<extra></extra>")) %>% add_annotations(data = df, x = ~model, y = ~cost, text = ~cost, bgcolor = "white", bordercolor = "black", xshift = 15, yshift = 15, showarrow = F) %>% layout(barmode = "group")
效果对比
- 当前运行输出:

- 预期输出效果:

实现方法
只需要在add_lines()层中添加配置,单独为cost对应的图例标记设置黑色边框即可,不需要修改图中折线的显示样式。
推荐方案(高版本plotly适用)
直接使用legendmarker参数单独控制图例标记样式,不会对图中折线产生任何影响,修改后的add_lines()部分代码如下:
add_lines(inherit = F, data = df, x = ~model, y = ~cost, color = I("red"), name = "cost", # 为图例中的cost标识添加1px宽的黑色边框 legendmarker = list(bordercolor = "black", borderwidth = 1), hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>", "Name: cost<extra></extra>"))
低版本兼容方案
如果使用的plotly版本较低不支持legendmarker参数,可以给折线层添加极小尺寸的标记,仅让标记的黑色边框在图例中显示,不会影响折线本身的展示效果,代码如下:
add_lines(inherit = F, data = df, x = ~model, y = ~cost, color = I("red"), name = "cost", mode = "lines+markers", marker = list( color = "red", # 标记设置黑色边框 line = list(color = "black", width = 1), # 标记大小设为0.1,图上几乎不可见,仅在图例中生效 size = 0.1 ), hovertemplate = paste0("Model: %{x}<br>Value: %{y}<br>", "Name: cost<extra></extra>"))
把对应部分替换到原代码中,运行即可得到预期的图例效果。
内容的提问来源于stack exchange,提问作者user18937485
相关产品推荐
相关产品推荐

