Osm*_*hop 28 python matplotlib legend legend-properties pandas
我在matplotlib中生成一些图,并希望为某些数据添加解释性文本.我希望在我的图例中有一个字符串作为'0-10'项目上方的单独图例项目.有谁知道是否有可能这样做?
这是我的传奇代码:
ax.legend(['0-10','10-100','100-500','500+'],loc='best')
Cle*_*H. 43
替代解决方案,有点脏但很快.
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()
Run Code Online (Sandbox Code Playgroud)
Jef*_*ner 37
当然.ax.legend()
有一个两个参数形式,接受一个对象列表(句柄)和一个字符串列表(标签).使用虚拟对象(也称为"代理艺术家")来获取额外的字符串.我选择了一个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()
Run Code Online (Sandbox Code Playgroud)
小智 18
我找到了另一种方法来做到这一点,只需尝试:
plt.legend(title='abc xyz')
Run Code Online (Sandbox Code Playgroud)
我在工作中用过这个!