我想将图例的项目形状从线条更改为任何其他吸引人的形状,例如盒子或圆形。 下面是我的图表。您可以看到图例项显示一条彩色线。不太吸引人。
如何在不更改图表类型的情况下更改图例项的形状?
下面是我的图例所需的项目形状的示例。
您最好的选择是:
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()
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