Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom legend in Pandas bar plot (matplotlib)

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.

enter image description here

like image 986
Vasilis Avatar asked Apr 15 '15 01:04

Vasilis


People also ask

Can a legend be drawn in a bar plot MatPlotLib?

In R you can add a legend to any plot using the legend() command. You can also use the legend = TRUE parameter in the barplot() command. The barplot() command is the only general plot type that has a legend parameter (the others need a separate legend).

How do you make a legend on a bar graph in Python?

Create a list of data x3, y3, z3, dx, dy and dz using numpy. Plot a 3D bar using bar3d() method. Create a rectangle axis for legend placement. Use legend() method to place the legend for bars.

How do you change the legend in pandas plot?

Make a dictionary d with keys Column1 and Column2. Make a data frame using DataFrame (d). Plot the data frame with a list of styles. Using legend(), place a legend on the figure.


1 Answers

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()
like image 98
Bob Haffner Avatar answered Oct 19 '22 19:10

Bob Haffner