Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

python - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...