Plotly。如何更改图例项目名称?

问题描述 投票:1回答:1

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

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

enter image description here

因为我给物种分配了自己的颜色,我想重新命名图例,这样它就不会出现'#c9cba3', '#ffe1a8' & '#e26d5c'.

python plotly plotly-python
1个回答
2
投票

重命名你的图例元素不会帮助你。在 px.scatter()జజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ color 参数与实际的颜色没有什么关系,而是在pandas数据框架中的哪个变量中寻找唯一的值来分配一个共同的颜色。看看当你把你的:

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

...到。

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

在你的示例图中,颜色是非常相同的,因为我最初解释过了。

enter image description here

要在你的情况下实际指定颜色,使用 color_discrete_map=dict() 并使用color 对于 species 变量。这样你就可以 其实 定义你所需要的颜色,你就不用重新命名你的图例元素了。

剧情。

enter image description here

完整的代码。

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()
© www.soinside.com 2019 - 2024. All rights reserved.