从dataframe.plot更改堆叠条形图中的颜色

2024-06-02 10:15:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要能够更改此堆叠条形图中每个条形的颜色:

enter image description here

目前的代码是:

my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] 
ax = df.T.plot(kind='bar', stacked=True,color = my_colors,alpha = 0.8,width = 0.7)

Dataframe有多个列,每列有两行

“我的颜色”列表如何更改条形图每个部分的颜色


Tags: 代码indfforlenplot颜色my
1条回答
网友
1楼 · 发布于 2024-06-02 10:15:03

如果从多个列(或行)绘制条形图并使用transpose.T,pandas将为每个列指定不同的颜色。所以在你的箱子里只有两种不同的颜色。将使用颜色列表的前两个元素

如果每个条需要单独的颜色,则需要打印两次。第二次使用另一个作为底部

一些示例代码显示了它的工作原理:

import matplotlib.pyplot as plt
import pandas as pd
import random

d = {a: [random.randint(2, 5), random.randint(3, 7)] for a in list('abcdefghij')}

df = pd.DataFrame(d)
my_colors0 = [plt.cm.plasma(i / len(df.columns) / 2 + 0.5) for i in range(len(df.columns))]
ax = df.T[0].plot(kind='bar', color=my_colors0, width=0.7)
my_colors1 = [plt.cm.plasma(i / len(df.columns) / 2) for i in range(len(df.columns))]
ax = df.T[1].plot(kind='bar', bottom=df.T[0], color=my_colors1, width=0.7, ax=ax)

plt.show()

sample plot

相关问题 更多 >