覆盖图例显示的跟踪属性

问题描述 投票:0回答:1

如何强制plotly 5.9图的图例使用与迹线定义的参数不同的参数?

我有一个覆盖低不透明度数据点的散点图,我希望图例以完全不透明度显示颜色。另外,我想增加图例中的标记大小。我不知道如何访问这些属性。

这是我创建绘图的方式:

import numpy as np
import plotly.graph_objs as go
from plotly.offline import plot
from plotly.subplots import make_subplots
from IPython.display import display, HTML

x = np.random.rand(2000)
y1 = np.random.rand(2000)
y2 = np.random.randn(2000)

fig = make_subplots(rows=1, cols=2)
 

trc1 = go.Scatter(x=x, y=y1, mode='markers', marker=dict(
    color='blue', size=2, opacity=0.2)
)
trc2 = go.Scatter(x=x, y=y2, mode='markers', marker=dict(
    color='green', size=4, opacity=0.2)
)

fig.add_trace(trc1, row=1, col=1)
fig.add_trace(trc2, row=1, col=2)

# This raises ValueError: Invalid property 'marker'
#fig.update_layout(legend=dict(marker=dict(opacity=1)))

# This works, but also updates the plots
#fig.for_each_trace(lambda t: t.update(marker=dict(opacity=1)))

display(HTML(plot(fig, output_type="div")))

编辑:仅针对标记大小,解决方案是

fig.update_layout(legend={'itemsizing': 'constant'})

但是如何调整不透明度(或标记的任何其他属性)?

python plotly
1个回答
0
投票

无法直接使用 Plotly API 来执行此操作,但您可以将

post_script
(将覆盖相关 HTML 元素样式的 JavaScript 片段)传递给函数
plotly.io.to_html()

对于语法高亮,这里是单独的 JS 代码:

const gd = document.querySelector('.plotly-graph-div');

// Override opacity of legend layers (fill, lines, marker symbols)
const setLegendOpacity = () => {
  gd.querySelectorAll('.legend .layers path').forEach(el => {
    el.style.opacity = 1; // marker symbols
    el.strokeOpacity = 1; // fill, lines
  });
}

// Apply once 
setLegendOpacity();

// Reapply when needed 
gd.on('plotly_relayout', setLegendOpacity);
gd.on('plotly_restyle', setLegendOpacity);

现在在Python中:

js = '''
const gd = document.querySelector('.plotly-graph-div');

// Override opacity of legend layers (fill, lines, marker symbols)
const setLegendOpacity = () => {
  gd.querySelectorAll('.legend .layers path').forEach(el => {
    el.style.opacity = 1; // marker symbols
    el.strokeOpacity = 1; // fill, lines
  });
}

// Apply once 
setLegendOpacity();

// Reapply when needed 
gd.on('plotly_relayout', setLegendOpacity);
gd.on('plotly_restyle', setLegendOpacity);
'''

# display(HTML(plot(fig, output_type="div")))
 
display(HTML(pio.to_html(
    fig,
    post_script=[js],
    full_html=False,
    include_plotlyjs=True
)
© www.soinside.com 2019 - 2024. All rights reserved.