Reputation: 2832
I have created a bar plot with Pandas where I show how a quantity change for some countries and I set the bar color according to each country's continent. I plot the graph using the following code. The code is based on the second reply of this question:
s = pd.Series(
listOfQuantities,
listOfCountiesNames
)
''' Assign color to each country based on the continent '''
colormapping = {'AF':'k','AS':'r','EU':'g','OC':'r','NA':'b','SA':'y'}
colorstring = ""
for country in listOfCountiesNames:
continent = countryToContinent[country]
colorstring += colormapping[continent]
pd.Series.plot(
s,
kind='bar',
color=colorstring,
grid=False,
)
I want to create a legend like the one I show in the attached image (the legend wasn't generated by python, I added manually). Is it possible to draw such custom legends with pandas, or can I achieve something similar with other graphing libraries? Also I'd appreciate suggestions for alternative plot types for such type of data.
Upvotes: 15
Views: 14024
Reputation: 8483
So after your Series plot you could add this
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
NA = mpatches.Patch(color='blue', label='North America')
EU = mpatches.Patch(color='green', label='Europe')
AP = mpatches.Patch(color='red', label='Asia/Pacific')
SA = mpatches.Patch(color='yellow', label='South America')
plt.legend(handles=[NA,EU,AP,SA], loc=2)
plt.show()
Upvotes: 34