You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Plotly图例符号从线条修改为方形?

将Plotly图例符号改为方形的方法

你可以通过两种简单方式实现将图例符号从线条改为方形:

方法1:添加trace时单独设置图例符号

在创建go.Scatter对象时,直接添加legend_symbol="square"参数,指定该trace的图例符号为方形:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

def save_fig(fig,pngname):
    fig.write_image(pngname,format="png",width=600,height=400, scale=1)
    print("[[%s]]"%pngname)
    return

df = px.data.stocks()
df = df[['date','AMZN', 'AAPL']]

fig = go.Figure()
for name in df.columns:
    if name == 'date': continue
    trace = go.Scatter(
        x = df['date'],
        y = df[name],
        name=name,
        legend_symbol="square"  # 设置图例符号为方形
    )
    fig.add_trace(trace)
        
save_fig(fig,"./demo.png")

方法2:批量更新所有trace的图例符号

如果已经创建完所有trace,可通过fig.update_traces()方法统一修改所有图例符号,无需逐个调整:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

def save_fig(fig,pngname):
    fig.write_image(pngname,format="png",width=600,height=400, scale=1)
    print("[[%s]]"%pngname)
    return

df = px.data.stocks()
df = df[['date','AMZN', 'AAPL']]

fig = go.Figure()
for name in df.columns:
    if name == 'date': continue
    trace = go.Scatter(
        x = df['date'],
        y = df[name],
        name=name,
    )
    fig.add_trace(trace)

# 统一设置所有trace的图例符号为方形
fig.update_traces(legend_symbol="square")
        
save_fig(fig,"./demo.png")

补充说明:legend_symbol参数支持多种符号取值,比如circle、diamond等,可根据需求替换。

内容的提问来源于stack exchange,提问作者lucky1928

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:14:56