我被要求使用以下数据制作条形图:
customer=['Alice', 'Bob', 'Claire']
cakes=[5,9,7]
flavor=['chocolate', 'vanilla', 'strawberry']
使用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()
我的问题是: 如何更优雅地为图例指定多个标签和颜色?
也请给我一些建议,让我如何设计这段代码,使它更加优雅和简洁,谢谢你,很抱歉问了这么长的问题
由于您要自定义太多的内容,例如颜色、名称,尤其是每个条的图例标签,我看不到任何明显更好的解决方案。一个轻微的改进是删除
length/y_pos
:输出:
相关问题 更多 >
编程相关推荐