【问题标题】:Change colors in stacked barplot from dataframe.plot从 dataframe.plot 更改堆积条形图中的颜色
【发布时间】:2020-05-21 05:58:01
【问题描述】:

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

目前的代码是:

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 列表必须如何更改条形图每个部分的颜色?

【问题讨论】:

  • 请注意,在您的情况下,len(df) 是 2,因为只有两行。 len(df.columns) 将是 11。这两种颜色 (0/10.0, 0/20.0, 0.75) 和 (1/10.0, 1/20.0, 0.75) 看起来非常相似。

标签: python pandas dataframe matplotlib


【解决方案1】:

如果您从多列(或多行并使用转置 .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()

【讨论】:

  • 这能回答你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 2017-09-29
  • 2017-03-31
  • 1970-01-01
相关资源
最近更新 更多