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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16826711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:46:43  来源:igfitidea点击:

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

pythonmatplotlibpandaslegendlegend-properties

提问by Osmond Bishop

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?

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

enter image description here

在此处输入图片说明

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

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

采纳答案by Jeff Tratner

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.Rectanglewith no fill and 0 linewdith below, but you could use any supported artist.

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

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

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

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

示例输出

回答by Clement H.

Alternative solution, kind of dirty but pretty quick.

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

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

在此处输入图片说明