Plotly:如何更改图例项名称?

Plotly: How to change legend item names?

我想更改图例中项目的名称。下面是一个可重现的例子。

import plotly.express as px
df = px.data.iris()
colorsIdx = {'setosa': '#c9cba3', 'versicolor': '#ffe1a8',
             'virginica': '#e26d5c'}
cols      = df['species'].map(colorsIdx)

fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
              color=cols)
fig.show()

因为我将自己的颜色分配给了我想重命名图例的物种,所以它不会显示为“#c9cba3”、“#ffe1a8”和“#e26d5c”。相反,我想成为 "setosa" "versicolor" & "virginica"

一般你可以使用:

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

在你的情况下 newnames 将是 dict:

{'#c9cba3': 'setosa', '#ffe1a8': 'versicolor', '#e26d5c': 'virginica'}

并且您已经在 colorsIdx 中指定了具有类似信息的字典,所以您只需要 switch keys and values 和:

newnames = {y:x for x,y in colorsIdx.items()}

但是,您应该知道这里还有更多内容!在 px.scatter() 中,color 参数与实际颜色几乎没有关系,而是 pandas 数据框中的哪个变量来寻找唯一值以分配颜色。看看当你改变你的时会发生什么:

colorsIdx = {'setosa': '#c9cba3', 'versicolor': '#ffe1a8',
             'virginica': '#e26d5c'}

...至:

colorsIdx = {'setosa': '#magic', 'versicolor': '#color',
             'virginica': '#function'}

由于我最初解释的原因,您的示例图中的颜色非常相同:

要根据您的情况实际指定颜色,请使用 color_discrete_map=dict() 并使用 color 作为 species 变量。这样您就可以实际定义您想要的颜色,而不必重命名您的图例元素。

剧情:

完整代码:

import plotly.express as px
df = px.data.iris()

fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
              color='species',
              color_discrete_map={'setosa': 'steelblue', 
                                  'versicolor': 'firebrick',
                                  'virginica': 'green'})
fig.show()