繁体   English   中英

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

[英]Change colors in stacked barplot from dataframe.plot

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

在此处输入图片说明

目前的代码是:

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 有多个列,每列有两行。

my_colors 列表如何喜欢更改条形图每个部分的颜色?

如果您从多列(或多行并使用转置 .T)绘制条形图,pandas 将为每一列分配不同的颜色。 所以在你的情况下只有 2 种不同的颜色。 将使用颜色列表的前两个元素。

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

一些示例代码来展示它是如何工作的:

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

样地

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM