1

我正在尝试为 plotly express 条形图中的某些条形设置不同的颜色:

import plotly.express as px
import pandas as pd

data = {'Name':['2020/01', '2020/02', '2020/03', '2020/04',  
         '2020/05', '2020/07', '2020/08'],  
        'Value':[34,56,66,78,99,55,22]}
df = pd.DataFrame(data)

color_discrete_sequence = ['#ec7c34']*len(df)
color_discrete_sequence[5] = '#609cd4'
fig=px.bar(df,x='Name',y='Value',color_discrete_sequence=color_discrete_sequence)
fig.show()

我的期望是一个(第六个)条有不同的颜色,但是我得到了这个结果:

在此处输入图像描述

我究竟做错了什么?

4

1 回答 1

1

发生这种情况是因为colorinpx.bar用于命名类别以使用色标来说明数据集的特征或维度。或者在你的情况下,而不是颜色循环,因为你正在处理一个分类/离散的情况。color_discrete_sequence然后用于指定要遵循的颜色序列。使用此处的设置实现目标的一种方法是简单地定义一个具有唯一值的字符串变量,例如 like df['category'] [str(i) for i in df.index],然后使用:

fig=px.bar(df,x='Name',y='Value',
           color = 'category',
           color_discrete_sequence=color_discrete_sequence,
           )

阴谋:

在此处输入图像描述

Ifdf['category']是一个数值,color_discrete_sequence将被忽略,并应用默认的连续序列:

在此处输入图像描述

如果还有其他不清楚的地方,请随时告诉我。

完整代码:

import plotly.express as px
import pandas as pd

data = {'Name':['2020/01', '2020/02', '2020/03', '2020/04',  
         '2020/05', '2020/07', '2020/08'],  
        'Value':[34,56,66,78,99,55,22]}
df = pd.DataFrame(data)
df['category'] = [str(i) for i in df.index]
# df['category'] = df.index

color_discrete_sequence = ['#ec7c34']*len(df)
color_discrete_sequence[5] = '#609cd4'
fig=px.bar(df,x='Name',y='Value',
           color = 'category',
           color_discrete_sequence=color_discrete_sequence,
           )
fig.show()
于 2021-09-11T23:01:42.407 回答