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
81 views
in Technique[技术] by (71.8m points)

python - Is it possible to add a string as a legend item in matplotlib

I am producing some plots in matplotlib and would like to add explanatory text for some of the data. I want to have a string inside my legend as a separate legend item above the '0-10' item. Does anyone know if there is a possible way to do this?

enter image description here

This is the code for my legend:
ax.legend(['0-10','10-100','100-500','500+'],loc='best')

question from:https://stackoverflow.com/questions/16826711/is-it-possible-to-add-a-string-as-a-legend-item-in-matplotlib

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

1 Reply

0 votes
by (71.8m points)

Sure. ax.legend() has a two argument form that accepts a list of objects (handles) and a list of strings (labels). Use a dummy object (aka a "proxy artist") for your extra string. I picked a matplotlib.patches.Rectangle with no fill and 0 linewdith below, but you could use any supported artist.

For example, let's say you have 4 bar objects (since you didn't post the code used to generate the graph, I can't reproduce it exactly).

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig = plt.figure()
ax = fig.add_subplot(111)
bar_0_10 = ax.bar(np.arange(0,10), np.arange(1,11), color="k")
bar_10_100 = ax.bar(np.arange(0,10), np.arange(30,40), bottom=np.arange(1,11), color="g")
# create blank rectangle
extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
ax.legend([extra, bar_0_10, bar_10_100], ("My explanatory text", "0-10", "10-100"))
plt.show()

example output


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

...