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

44

我想在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()

这将产生:

enter image description here

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

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

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


非常好的答案,它完成了工作。我希望你构建的功能已经是plotly express模块的一部分了,但从你的回答中我理解到这并不是这种情况? - emil banning
5个回答

46

答案:

如果不更改数据源,则需要完全替换legendlegendgrouphovertemplate中的名称,具体操作如下:

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

情节:

enter image description here

详细信息:

使用

fig.for_each_trace(lambda t: t.update(name = newnames[t.name]))

使用字典可以在不更改源代码的情况下更改图例中的名称。

newnames = {'col1':'hello', 'col2': 'hi'}

在以下图表结构的部分(对于您的第一个跟踪,col1),将新名称映射到现有的col1col2

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

1
谢谢你提供的解决方案,它可以对图例中的名称起作用。然而,在将鼠标移动到曲线上时,显示在框中的名称仍然是旧的,而不是新的。有任何解决方法吗? - Mathador
1
这里是解决方案,函数customLegend需要扩展如下:def customLegendPlotly(fig, nameSwap): for i, dat in enumerate(fig.data): for elem in dat: if elem == 'hovertemplate': fig.data[i].hovertemplate = fig.data[i].hovertemplate.replace(fig.data[i].name, nameSwap[fig.data[i].name]) for elem in dat: if elem == 'name': fig.data[i].name = nameSwap[fig.data[i].name] return fig - Mathador
有没有办法以LaTeX格式输出名称?例如,我想将r'$a+b$'格式化为LaTeX,但它只显示"$a+b$"。 - undefined

33

添加“name”参数: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
жҳҜзҡ„пјҢдҪҶжҳҜиҝҷз§Қи§ЈеҶіж–№жЎҲд»…йҖӮз”ЁдәҺдҪҝз”Ёplotly.graph_objectsеҲӣе»әзҡ„еӣҫеҪўпјҢиҖҢOPзҡ„й—®йўҳдёҺplotly.expressжңүе…ігҖӮ - callmeanythingyouwant

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

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”(自定义名称)的字典,并将原始跟踪名称映射到自定义名称。

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

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接