infomaniac
infomaniac

Reputation: 41

How do I assign multiple labels and colors on a legend in a bar graph in Matplotlib?

I was asked to make a bar chart using this data:

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

The end result should appear like this. enter image description here

The code to create the chart using Altair is as follows:

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()

The code I used to generate a similar chart using matplotlib is as follows:

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()

My question is: How may I more elegantly assign multiple labels and colors to a legend?

Please also give me suggestions as to how I may design this code so that it is more elegant and concise, thank you and sorry for such a long question!

Upvotes: 0

Views: 1785

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Since you are customize too many things, e.g. color, name, and especially legend label for each bar, I don't see any significantly better solution. One slight improvement is to remove 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()

Output:

enter image description here

Upvotes: 2

Related Questions