我正在 matplotlib 中生成一些图,并希望为某些数据添加解释性文本。我想在我的图例中有一个字符串作为 '0-10' 项上方的单独图例项。有人知道是否有可能的方法来做到这一点?
这是我的传奇代码:ax.legend(['0-10','10-100','100-500','500+'],loc='best')
当然。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()

我找到了另一种方法来做到这一点只是尝试:
plt.legend(title='abc xyz')
I used this in my work!
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(18条)