Plotly:如何将折线图中的图例项形状从线更改为框或圆形?

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

我想将图例的项目形状从线条更改为任何其他吸引人的形状,例如盒子或圆形。 下面是我的图表。您可以看到图例项显示一条彩色线。不太吸引人。

如何在不更改图表类型的情况下更改图例项的形状?

下面是我的图例所需的项目形状的示例。

python plotly data-visualization plotly-dash plotly-python
2个回答
2
投票

您最好的选择是: fig.layout.legend.itemsizing = 'constant'

这将为您提供以下图例,其中的项目至少看起来更像一个盒子或矩形而不是一条线:

而不是这个:

一些细节:

图例的形状默认反映轨迹的形状。这也适用于标记符号的大小和形状。所以如果你构建一个像这样的情节:

然后您可以随时更改图例的显示方式:

fig.data[0].mode = 'markers+lines' fig.data[0].marker.symbol = 'diamond' fig.data[0].marker.size = 12

但问题是,这适用于图形轨迹,您可以在这里看到:

我已经做了一些尝试来设置标记符号,然后删除痕迹的标记,以

希望

保留图例中的标记。但这是行不通的。我认为我们都会因此而变得更好。所以这就是我最初的建议。 完整代码:

# imports import pandas as pd import plotly.express as px # data df = px.data.stocks() df = df.drop(['AMZN', 'AAPL', 'MSFT', 'FB'], axis = 1) colors = px.colors.qualitative.T10 # plotly fig = px.line(df, x = 'date', y = [c for c in df.columns if c != 'date'], template = 'plotly_dark', color_discrete_sequence = colors, title = 'Stocks', ) fig.data[0].mode = 'markers+lines' fig.data[0].marker.symbol = 'diamond' fig.data[0].marker.size = 12 fig.layout.legend.itemsizing = 'constant' fig.show()



0
投票

var trace1 = { name: 'trace1', x: [1, 2, 3, 4], y: [10, 15, 13, 17], type: 'scatter', mode: 'lines', marker: { color: 'orange' }, // Set the legendgroup per trace. // Use this legendgroup with the corresponding shape so clicking the shape's legend will toggle the trace. legendgroup: 'trace1', // Don't show the legend for the trace so only the shape's legend is visible. showlegend: false, }; var trace2 = { name: 'trace2', x: [1, 2, 3, 4], y: [16, 5, 11, 9], type: 'scatter', mode: 'lines', marker: { color: 'blue' }, legendgroup: 'trace2', showlegend: false, }; var data = [trace1, trace2]; var shapes = data.map((trace) => ({ name: trace.name, // The shape should match the trace's legend group so it will toggle the shape and the trace as a group. legendgroup: trace.legendgroup, // Show the shape's legend. showlegend: true, type: 'rect', // For sanity, render the shape behind the lines. // But this shouldn't be necessary because the shape will never get plotted on the graph. See the xn configuration below. layer: 'below', // If you don't want a border around your legend's symbol, set the line.width to 0. line: { width: 0 }, // The fillcolor should match the trace's marker/line color. fillcolor: trace.marker.color, // Set the plot points of the shape to 0 so it won't be rendered on the graph. x0: 0, y0: 0, x1: 0, y1: 0, })); var layout = { shapes }; Plotly.newPlot('myDiv', data, layout);

您可以在这里看到它的实际效果:
https://codepen.io/freerange/pen/oNJQeEz

© www.soinside.com 2019 - 2024. All rights reserved.