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

emi*_*ing 10 python label plotly

我想在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()
Run Code Online (Sandbox Code Playgroud)

其中产生:

在此处输入图片说明

我想将标签名称从col1更改为hello并将col2更改为hi。我曾尝试在图中使用标签,但无法使其正常工作:

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

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

And*_*ndi 14

这段代码比较简洁。

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()
Run Code Online (Sandbox Code Playgroud)


ves*_*and 11

答案:

在不更改数据源的情况下,完全替换图例、图例组和悬停模板中的名称将需要:

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])
                                     )
                  )
Run Code Online (Sandbox Code Playgroud)

阴谋:

在此处输入图片说明

细节:

使用

fig.for_each_trace(lambda t: t.update(name = newnames[t.name]))
Run Code Online (Sandbox Code Playgroud)

...您可以使用 dict 更改图例中的名称,而无需更改源

newnames = {'col1':'hello', 'col2': 'hi'}
Run Code Online (Sandbox Code Playgroud)

...并将新名称映射到现有的col1col2图形结构的以下部分(对于您的第一次跟踪,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'},
Run Code Online (Sandbox Code Playgroud)

但是正如您所看到的,这对 和 没有任何作用'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])
                                     )
                  )
Run Code Online (Sandbox Code Playgroud)


Nic*_*aro 7

添加“名称”参数: 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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 是的,但是这个解决方案仅适用于使用“plotly.graph_objects”创建的图形,而OP的查询必须与“plotly.express”有关 (11认同)