是否可以在matplotlib中将字符串添加为图例项 [英] Is it possible to add a string as a legend item in matplotlib

查看:89
本文介绍了是否可以在matplotlib中将字符串添加为图例项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在matplotlib中生成一些图,并想为某些数据添加说明性文字.我想在图例中包含一个字符串,作为"0-10"项上方的单独图例项.有谁知道有没有办法做到这一点?

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?

这是我的图例代码:
ax.legend(['0-10','10-100','100-500','500+'],loc='best')

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

推荐答案

好的. ax.legend()具有两个参数形式,该形式接受对象列表(句柄)和字符串列表(标签).为多余的字符串使用虚拟对象(又称为代理艺术家" ).我在下面选择了一个matplotlib.patches.Rectangle没有填充和0 linewdith,但是您可以使用任何受支持的歌手.

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.

例如,假设您有4个条形对象(由于您没有发布用于生成图形的代码,因此我无法完全重现它).

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

这篇关于是否可以在matplotlib中将字符串添加为图例项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆