传递颜色时,在 Plotly Python 中保留原始条形顺序

Retain original bar order in Plotly Python when also passing color

使用 Plotly 绘制条形图在不使用时保留数据集的顺序 color:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'val': [1, 2, 3],
                   'type': ['b', 'a', 'b']},
                  index=['obs1', 'obs2', 'obs3'])
px.bar(df, 'val')

但是 color 重新排序数据:

px.bar(df, 'val', color='type')

如何在使用 color arg 时保留原始顺序?

这类似于 ,但我使用的是 Python 而不是 R。

我真的不知道为什么 plotly express 这样做,但你可以使用一个变通方法,如使用数组重新排序 yaxis fig.update_layout( yaxis={'categoryorder':'array', 'categoryarray':df.index}):

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'val': [1, 2, 3],
                   'type': ['b', 'a', 'b']},
                  index=['obs1', 'obs2', 'obs3'])
fig=px.bar(df, x='val',y=df.index, orientation='h')


fig=px.bar(df, x='val',y=df.index, color='type', orientation='h')
fig.update_layout( yaxis={'categoryorder':'array', 'categoryarray':df.index})

结果:

您可以使用 category_orders 参数:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'val': [1, 2, 3],
                   'type': ['b', 'a', 'b']},
                  index=['obs1', 'obs2', 'obs3'])
fig = px.bar(df, 'val', color='type', category_orders={'index': df.index[::-1]})
fig.show()

输出

来自documentation:

This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired.

通过查看 code,似乎 color 被用作分组属性,所以这可能就是重新排序发生的原因。