如何在Matplotlib中的条形图中为图例指定多个标签和颜色?

2024-09-28 22:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我被要求使用以下数据制作条形图:

customer=['Alice', 'Bob', 'Claire']
cakes=[5,9,7] 
flavor=['chocolate', 'vanilla', 'strawberry']

最终结果应该是这样的enter image description here

使用Altair创建图表的代码如下:

import altair

data = altair.Data(customer=['Alice', 'Bob', 'Claire'], cakes=[5,9,7], flavor=['chocolate', 'vanilla', 'strawberry'])
chart = altair.Chart(data)
mark = chart.mark_bar()
enc = mark.encode(x='customer:N',y='cakes',color='flavor:N')
enc.display()

我使用matplotlib生成类似图表的代码如下:

import matplotlib.pyplot as plt

customers = ['Alice', 'Bob', 'Clair']
length = [0,1,2]
cakes = [5, 9, 7]
flavors = ['chocolate', 'vanilla', 'strawberry']
colors = ['brown', 'beige', 'magenta']

for w,x,y,z in zip(length, flavors, colors, cakes):
    plt.bar(w, z, color = y, align = 'center', alpha = 0.5, label = x)

plt.xticks(y_pos, customers)

plt.ylabel('Cakes')
plt.title('Customers')

plt.legend()
plt.show()

我的问题是: 如何更优雅地为图例指定多个标签和颜色?

也请给我一些建议,让我如何设计这段代码,使它更加优雅和简洁,谢谢你,很抱歉问了这么长的问题


Tags: 代码import图表pltcustomerbobmarkalice
1条回答
网友
1楼 · 发布于 2024-09-28 22:25:25

由于您要自定义太多的内容,例如颜色、名称,尤其是每个条的图例标签,我看不到任何明显更好的解决方案。一个轻微的改进是删除length/y_pos

for w,x,y,z in zip(customers, flavors, colors, cakes):
    plt.bar(w, z, color = y, align = 'center', alpha = 0.5, label = x)

plt.ylabel('Cakes')
plt.title('Customers')

plt.legend()
plt.show()

输出:

enter image description here

相关问题 更多 >