如何在 plotly express 折线图中更改图例的变量/标签名称

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

我想在 python 中更改 plotly express 中的变量/标签名称。我首先创建一个情节:

import pandas as pd
import plotly.express as px

d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
fig = px.line(df, x=df.index, y=['col1', 'col2'])
fig.show()

产生:

我想将标签名称从 col1 更改为 hello,从 col2 更改为 hi。我试过在图中使用标签,但我无法让它工作:

fig = px.line(df, x=df.index, y=['col1', 'col2'], labels={'col1': "hello", 'col2': "hi"})
fig.show()

但这似乎什么也没做,同时没有产生错误。显然,我可以通过更改列名来实现我的目标,但是我尝试创建的实际图并不能真正允许这样做,因为它来自几个不同的数据框。

python plotly label plotly-python
5个回答
37
投票

答案:

在不更改数据源的情况下,完全替换

legend
legendgroup
hovertemplate
中的名称将需要:

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]))

...您可以更改图例中的名称,而无需使用字典更改源代码

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])
                                     )
                  )

27
投票

添加“名称”参数:

go.Scatter(name=...)

来源https://plotly.com/python/figure-labels/

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    name="Name of Trace 1"       # this sets its legend entry
))


fig.add_trace(go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[1, 0, 3, 2, 5, 4, 7, 6, 8],
    name="Name of Trace 2"
))

fig.update_layout(
    title="Plot Title",
    xaxis_title="X Axis Title",
    yaxis_title="X Axis Title",
    legend_title="Legend Title",
    font=dict(
        family="Courier New, monospace",
        size=18,
        color="RebeccaPurple"
    )
)

fig.show()


11
投票

这段代码比较简洁

import pandas as pd
import plotly.express as px

df = pd.DataFrame(data={'col1': [1, 2, 3], 'col2': [3, 4, 5]})

series_names = ["hello", "hi"]

fig = px.line(data_frame=df)

for idx, name in enumerate(series_names):
    fig.data[idx].name = name
    fig.data[idx].hovertemplate = name

fig.show()

1
投票

如果你正在寻找更简洁的东西,这个功能就可以了-

def custom_legend_name(new_names):
    for i, new_name in enumerate(new_names):
        fig.data[i].name = new_name

然后在

fig.show()
之前,只需将包含您想要的名称的列表传递给函数,就像这样
custom_legend_name(['hello', 'hi'])

这是完整代码的样子-

def custom_legend_name(new_names):
    for i, new_name in enumerate(new_names):
        fig.data[i].name = new_name
        

import pandas as pd
import plotly.express as px

d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
fig = px.line(df, x=df.index, y=['col1', 'col2'])
custom_legend_name(['hello','hi'])
fig.show()

0
投票
import pandas as pd
import plotly.express as px

d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
fig = px.line(df, x=df.index, y=['col1', 'col2'])

在您需要创建名为“新”(自定义名称)的字典并将原始跟踪名称映射到自定义名称之后。

new = {'col1':'Front hello', 'col2': 'hi'}
fig.for_each_trace(lambda t: t.update(name = new[t.name]))
fig.show()

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