Plotly Express创建折线图后修改图例标签方法求助
修改Plotly Express折线图的图例标签
当使用px.line绘制多列数据时,图例默认显示原始列名,你可以通过两种方式修改这些标签:
方法一:提前重命名DataFrame列
在创建图表前直接修改DataFrame的列名,这样px.line会自动使用新列名作为图例标签:
import plotly.express as px import pandas as pd # 加载数据 df = pd.read_csv("C:/Users/nicho/OneDrive - stevens.edu/Summer Research/Charts/Natural_Gas_Storage/Data/storage.csv", skiprows=4) # 定义原列名与新标签的映射,按实际列名调整 column_name_mapping = { df.columns[1]: "2020 年度", df.columns[2]: "2021 年度", df.columns[3]: "2022 年度", # 继续添加需要修改的列 } # 重命名列 df = df.rename(columns=column_name_mapping) # 创建图表 fig = px.line(df, x="Week of", y=df.columns[1:], labels={"variable": "Year"}) fig.update_xaxes(autorange="reversed") fig.update_yaxes(title="Billion Cubic Feet") fig.update_layout(title="Lower 48 Weekly Working Gas in Underground Storage") fig.show()
方法二:创建图表后修改图例标签
如果不想修改原始DataFrame,可以在生成图表对象后,直接遍历每个trace(折线)修改其name属性:
import plotly.express as px import pandas as pd df = pd.read_csv("C:/Users/nicho/OneDrive - stevens.edu/Summer Research/Charts/Natural_Gas_Storage/Data/storage.csv", skiprows=4) fig = px.line(df, x="Week of", y=df.columns[1:], labels={"variable": "Year"}) fig.update_xaxes(autorange="reversed") fig.update_yaxes(title="Billion Cubic Feet") fig.update_layout(title="Lower 48 Weekly Working Gas in Underground Storage") # 自定义图例标签列表,顺序需与df.columns[1:]的列顺序一致 custom_legend_labels = ["2020 年度", "2021 年度", "2022 年度"] # 遍历每个trace替换名称 for trace, new_label in zip(fig.data, custom_legend_labels): trace.name = new_label fig.show()
注意事项
- 确保自定义标签的顺序和
df.columns[1:]的列顺序完全匹配,否则图例标签会对应错误的折线。 - 如果你只需要修改部分图例标签,可以单独指定对应的trace索引,比如
fig.data[0].name = "自定义标签"。
内容的提问来源于stack exchange,提问作者Nicholas Mirigliani
相关产品推荐
相关产品推荐

