是否可以在 matplotlib中添加一个字符串作为图例项

我正在 matplotlib 中生成一些图,并希望为某些数据添加解释性文本。我想在我的图例中有一个字符串作为 '0-10' 项上方的单独图例项。有人知道是否有可能的方法来做到这一点?

我正在 matplotlib 中生成一些图,并希望为某些数据添加解释性文本。我想在我的图例中有一个字符串作为 '0-10' 项上方的单独图例项。有人知道是否有可能的方法来做到这一点?

enter image description here

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

108

替代解决方案,有点脏,但很快。

import pylab as plt
X = range(50)
Y = range(50)
plt.plot(X, Y, label="Very straight line")
# Create empty plot with blank marker containing the extra label
plt.plot([], [], ' ', label="Extra label on the legend")
plt.legend()
plt.show()

enter image description here

52

当然。ax.legend()有一个接受对象列表(句柄)和字符串列表(标签)的两个参数形式。为您的额外字符串使用虚拟对象(又名"proxy artist")。我选择了一个matplotlib.patches.Rectangle,没有填充和 0 linewdith,但您可以使用任何支持的艺术家。

例如,假设您有 4 个 bar 对象(由于您没有发布用于生成图形的代码,因此我无法准确地重现它)。

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

7

我找到了另一种方法来做到这一点只是尝试:

plt.legend(title='abc xyz')

I used this in my work!

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(862)
如何在Asp.netWeb服务器端启动bat文件
上一篇
在verilog中定义一个常数(用于合成 )
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(58条)