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.
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).
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With