答案:
在不更改数据源的情况下,完全替换图例、图例组和悬停模板中的名称将需要:
newnames = {'col1':'hello', 'col2': 'hi'}
fig.for_each_trace(lambda t: t.update(name = newnames[t.name],
legendgroup = newnames[t.name],
hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])
)
)
剧情:
详情:
使用
fig.for_each_trace(lambda t: t.update(name = newnames[t.name]))
...您可以更改图例中的名称,而无需使用 dict 更改源
newnames = {'col1':'hello', 'col2': 'hi'}
...并将新名称映射到图形结构以下部分中的现有 col1 和 col2(对于您的第一个跟踪,col1):
{'hovertemplate': 'variable=col1<br>index=%{x}<br>value=%{y}<extra></extra>',
'legendgroup': 'col1',
'line': {'color': '#636efa', 'dash': 'solid'},
'mode': 'lines',
'name': 'hello', # <============================= here!
'orientation': 'v',
'showlegend': True,
'type': 'scatter',
'x': array([0, 1, 2], dtype=int64),
'xaxis': 'x',
'y': array([1, 2, 3], dtype=int64),
'yaxis': 'y'},
但正如您所见,这对'legendgroup': 'col1' 和'hovertemplate': 'variable=col1<br>index=%{x}<br>value=%{y}<extra></extra>' 没有任何作用,并且根据您的图形的复杂性,这可能会造成问题。所以我会添加 legendgroup = newnames[t.name] 和hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])。
完整代码:
import pandas as pd
import plotly.express as px
from itertools import cycle
d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
fig = px.line(df, x=df.index, y=['col1', 'col2'])
newnames = {'col1':'hello', 'col2': 'hi'}
fig.for_each_trace(lambda t: t.update(name = newnames[t.name],
legendgroup = newnames[t.name],
hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])
)
)