R语言Plotly中移除/重命名add_trace生成的图例及标题
Plotly 图例问题解决方案
需求说明
- 移除或重命名图例标题(红色标注处)
- 移除
add_trace生成的图例(常规showlegend = FALSE无效)
解决方案代码
library(tidyverse) library(plotly) Strat <- structure(list(GS.Open = c(200.600006, 200.220001, 198.429993, 199.050003, 203.539993, 203.399994, 208.339996, 210.899994, 210.850006, 212.199997, 213.75), GS.High = c(203.320007, 200.669998, 200, 203.949997, 204.899994, 208.440002, 213.169998, 214.220001, 215.130005, 214.089996, 214.809998), GS.Low = c(197.820007, 198.070007, 197.899994, 198.100006, 202, 201.5, 207.600006, 210.399994, 210.850006, 210.850006, 209.100006), GS.Close = c(200.720001, 198.850006, 199.050003, 203.729996, 204.080002, 208.110001, 211.880005, 213.990005, 213.589996, 213.229996, 209.679993), GS.Volume = c(6494900, 6460200, 5892900, 7851000, 7147100, 8025700, 9039400, 6618900, 5846600, 5306300, 6423200), GS.Adjusted = c(162.160843, 160.65007, 160.811646, 164.59259, 164.875336, 168.131134, 171.177002, 172.881592, 172.558426, 172.267532, 169.399551), date = c("2007-01-03", "2007-01-04", "2007-01-05", "2007-01-08", "2007-01-09", "2007-01-10", "2007-01-11", "2007-01-12", "2007-01-16", "2007-01-17", "2007-01-18"), level = c(200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200), level2 = c(250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250), points = -5:5), row.names = c("2007-01-03", "2007-01-04", "2007-01-05", "2007-01-08", "2007-01-09", "2007-01-10", "2007-01-11", "2007-01-12", "2007-01-16", "2007-01-17", "2007-01-18" ), class = "data.frame") Plot_Points <- Strat %>% filter((points <= -3 | points >= 3)) i <- list(line = list(color = '#6b998b')) d <- list(line = list(color = '#996b6b')) p <- Strat %>% plot_ly(x = ~date, type="candlestick", open = ~GS.Open, close = ~GS.Close, high = ~GS.High, low = ~GS.Low, increasing = i, decreasing = d, showlegend = FALSE) %>% # 隐藏K线的图例 add_trace(x = ~Plot_Points$date, y = ~Plot_Points$GS.Close, color = ~Plot_Points$points, type = "scatter", mode = 'markers', marker = list(size = 8, opacity = 0.8), showlegend = FALSE, # 隐藏散点分组的所有图例 hovertemplate = paste("Signal: %{marker.color:f}", "<extra></extra>")) %>% layout( plot_bgcolor='#343E48', paper_bgcolor='#343E48', font = list(color = 'grey'), # 处理图例标题:移除设为空字符串,重命名则替换为自定义文本 legend = list( title = list(text = "") # 移除图例标题;若重命名改为title = list(text = "自定义标题") ) ) p
关键修改说明
移除/重命名图例标题:
在layout中添加legend = list(title = list(text = "")),将text设为空字符串即可移除标题;若需要重命名,直接替换为自定义文本(如"信号值")。彻底移除
add_trace生成的图例:- 由于使用
color = ~Plot_Points$points会自动为每个不同的points值创建独立的trace,仅在add_trace中设置showlegend = FALSE即可让所有这些散点分组的图例项不显示。 - 同时给初始的candlestick trace添加
showlegend = FALSE,确保K线的图例也被隐藏(如果不需要的话)。
- 由于使用
内容的提问来源于stack exchange,提问作者Ian.T
相关产品推荐
相关产品推荐

