我正在使用 Matplotlib 绘制顶级客户图。我希望条形的颜色根据它们所在的区域而变化。目前我有列出每个区域并分配颜色的代码。有没有办法遍历区域并自动分配随机颜色,这样我就没有每个区域的冗余代码。
#此代码块适用于前 15 位客户。
plt.figure(figsize=(20,4))
mask1 = top_cust['region'] == 'South West'
mask2 = top_cust['region'] == 'South East'
mask3 = top_cust['region'] == 'North West'
mask4 = top_cust['region'] == 'West'
mask5 = top_cust['region'] == 'South'
mask6 = top_cust['region'] == 'East'
mask7 = top_cust['region'] == 'North'
mask8 = top_cust['region'] == 'North East'
mask9 = top_cust['region'] == 'Central'
plt.bar((top_cust['customer_name_first'])[mask1], (top_cust['profit'])[mask1], color = 'blue')
plt.bar((top_cust['customer_name_first'])[mask2], (top_cust['profit'])[mask2], color = 'red')
plt.bar((top_cust['customer_name_first'])[mask3], (top_cust['profit'])[mask3], color = 'green')
plt.bar((top_cust['customer_name_first'])[mask4], (top_cust['profit'])[mask4], color = 'black')
plt.bar((top_cust['customer_name_first'])[mask5], (top_cust['profit'])[mask5], color = 'yellow')
plt.bar((top_cust['customer_name_first'])[mask6], (top_cust['profit'])[mask6], color = 'teal')
plt.bar((top_cust['customer_name_first'])[mask7], (top_cust['profit'])[mask7], color = 'grey')
plt.bar((top_cust['customer_name_first'])[mask8], (top_cust['profit'])[mask8], color = 'orange')
plt.bar((top_cust['customer_name_first'])[mask9], (top_cust['profit'])[mask9], color = 'purple')
plt.title('Profits By Customer')
plt.xlabel('Customer')
plt.ylabel('Profits in Dollars')
plt.show()