matplotlib.pyplot.text设置label后图例为空且报错的问题咨询
问题描述
根据matplotlib文档说明,plt.text可通过label关键字参数让内容显示在图例中,但运行以下代码时,却出现警告No handles with labels found to put in legend.且图例为空,请问操作是否有误?
import matplotlib.pyplot as plt plt.text(0.25, 0.25, "1", bbox={"boxstyle" : "circle", "color":"grey"}, label = "Dude, where's my car?") plt.text(0.75, 0.75, "2", bbox={"boxstyle" : "circle", "color":"grey"}, label = "Nevermind, here it is.") plt.legend(loc = 'lower right')

问题原因
plt.legend()默认只会自动收集**线条类(Line2D)和补丁类(Patch)**的艺术家对象,Text对象不在默认的收集范围内,所以即便给plt.text设置了label参数,也不会被自动加入图例,从而触发警告并显示空图例。
解决方案
方案1:手动传入Text对象到图例
将创建的Text对象保存下来,在调用plt.legend()时通过handles参数手动指定要添加的元素:
import matplotlib.pyplot as plt # 保存创建的Text对象 txt1 = plt.text(0.25, 0.25, "1", bbox={"boxstyle" : "circle", "color":"grey"}, label = "Dude, where's my car?") txt2 = plt.text(0.75, 0.75, "2", bbox={"boxstyle" : "circle", "color":"grey"}, label = "Nevermind, here it is.") # 手动传入handles参数指定图例元素 plt.legend(handles=[txt1, txt2], loc='lower right')
这种方式的图例条目会和文本元素的样式一致(显示文本+灰色圆圈)。
方案2:使用虚拟补丁对象替代Text对象
如果只希望图例显示文本元素的bbox样式(比如仅显示灰色圆圈),可以创建与bbox样式匹配的虚拟Patch对象,再将其加入图例:
import matplotlib.pyplot as plt from matplotlib.patches import Circle plt.text(0.25, 0.25, "1", bbox={"boxstyle" : "circle", "color":"grey"}) plt.text(0.75, 0.75, "2", bbox={"boxstyle" : "circle", "color":"grey"}) # 创建与bbox样式匹配的虚拟补丁 patch1 = Circle((0,0), color='grey', label="Dude, where's my car?") patch2 = Circle((0,0), color='grey', label="Nevermind, here it is.") # 将虚拟补丁加入图例 plt.legend(handles=[patch1, patch2], loc='lower right')
内容的提问来源于stack exchange,提问作者ramzeek
相关产品推荐
相关产品推荐

