python - 如何为绘图条形图中的某些条设置特定颜色?

标签 python colors plotly bar-chart plotly-python

我正在尝试为 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()

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

enter image description here

我做错了什么?

最佳答案

发生这种情况是因为 px.bar 中的 color 用于命名类别,以使用色标说明数据集的特征或维度。或者在你的情况下,而不是颜色循环,因为你正在处理一个分类/离散的案例。 color_discrete_sequence 然后用于指定要遵循的颜色序列。使用此处的设置实现目标的一种方法是简单地定义具有唯一值的字符串变量,例如 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,
           )

plotly :

enter image description here

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

enter image description here

如果还有什么不清楚的,请随时告诉我。

完整代码:

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

关于python - 如何为绘图条形图中的某些条设置特定颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69146994/

相关文章:

python - PyPI - 包不包含文件

python - MySQL 返回列的名称而不是值

javascript - ATOM 代码编辑器中的彩色文本意味着什么?

linux - 通过不同颜色的变量打开emacs

javascript - 使用 Plotly 定义饼图切片颜色

python - 使用 CVXPY 求解拟凸问题

css - 使用 CSS 选择 2 悬停颜色

Python 警告 : plotly. graph_objs.Line 已弃用

python - 阴谋冲刺 : How to add footnotes and source text to plots

python - pylint 父类(super class) __init__ 误报