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

2022-01-21 00:00:00 python plotly label

问题描述

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

I want to change the variable/label names in plotly express in python. I first create a plot:

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.我试过在图中使用标签,但我无法让它工作:

I want to change the label names from col1 to hello and from col2 to hi. I have tried using labels in the figure, but I cannot get it to work:

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

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

But this seems to do nothing, while not producing an error. Obviously I could achieve my goals by changing the column names, but the actual plot i'm trying to create doesn't really allow for that since it comes from several different dataframes.


解决方案

答案:

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

The answer:

Without changing the data source, a complete replacement of names both in the legend, legendgroup and hovertemplate will require:

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 更改源

...you can change the names in the legend without ghanging the source by using a dict

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

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

...and map new names to the existing col1 and col2 in the following part of the figure structure (for your first trace, 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]).

But as you can see, this doesn't do anything with 'legendgroup': 'col1', nor 'hovertemplate': 'variable=col1<br>index=%{x}<br>value=%{y}<extra></extra>' And depending on the complexity of your figure, this can pose a problem. So I would add legendgroup = newnames[t.name] and hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])into the mix.

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

相关文章