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

时间:2020-02-05 10:30:34

标签: python pandas dataframe matplotlib

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

enter image description here

当前代码为:

import getpass
from exchangelib import Configuration
from exchangelib import Credentials, Account

def login():
    email = 'user@domain.com'
    passwd = getpass.getpass(prompt='Password: ')
    user_credentials = Credentials(email, passwd)
    config = Configuration(server='exchangeserver',
                           credentials=user_credentials)
    account = Account(primary_smtp_address=email, config=config,
                           credentials=user_credentials, autodiscover=False) #maybe try =True
    return account

def main():
    user_account = authenticate()
    print(user_account.root.tree()) #printing the inbox

main()
input('Press enter to exit')

数据框具有多列,每列两行。

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

1 个答案:

答案 0 :(得分:1)

如果从多列(或多行)中绘制条形图并使用转置.T,熊猫将为每列分配不同的颜色。因此,您的情况下只有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()

sample plot