Skip to main content
 首页 » 编程设计

python之调整条形图上的颜色编码,以便在 matplotlib 中对所有值进行正确的颜色编码

2024年09月07日6youxin

我有一个条形图,按州和类别(有 5 个类别)绘制利率,但问题是某些州的类别比其他州多。

import pandas as pd 
import matplotlib.pyplot as plt 
 
 
df = pd.DataFrame({"state" : ["AL","AL","AL","AK", ], 
                   "status" : ["Booked", "Rejected","Cancelled","Rejected"], 
                   "0" : [1.5,2.5,3.5,1.0]}) 
 
df2 = df.groupby(['state','status']).size()/df.groupby(['state']).size() 
 
fig, ax = plt.subplots() 
plt.xlabel('State') 
plt.ylabel('Bookings') 
 
my_colors = 'gyr' 
df2.plot(kind='bar', color=my_colors, orientation='vertical') 
 
plt.tight_layout() 
plt.show() 

这对我需要做的大部分工作都做得很好,但是,发生的情况是,因为某些州没有 status 的所有值,因此没有出现在图中,它使得一些颜色编码不正确,因为颜色只是转移到每 5 种颜色重复一次,而不是根据是否缺少值。我该怎么办?

请您参考如下方法:

您可能希望以分组方式显示数据,即每组有 3 个类别,这样每个类别都有自己的颜色。

在这种情况下,这似乎可以通过拆分多索引数据帧轻松实现,

df2.unstack().plot(...) 

完整示例:

import pandas as pd 
import matplotlib.pyplot as plt 
 
 
df = pd.DataFrame({"state" : ["AL","AL","AL","AK", ], 
                   "status" : ["Booked", "Rejected","Cancelled","Rejected"], 
                   "0" : [1.5,2.5,3.5,1.0]}) 
 
df2 = df.groupby(['state','status']).size()/df.groupby(['state']).size() 
 
fig, ax = plt.subplots() 
plt.xlabel('State') 
plt.ylabel('Bookings') 
 
my_colors = 'gyr' 
df2.unstack().plot(kind='bar', color=my_colors, orientation='vertical', ax=ax) 
 
plt.tight_layout() 
plt.show()