在图例,matplotlib,Python中使用代理艺术家 [英] Using a proxy artist inside a legend, matplotlib, Python

查看:108
本文介绍了在图例,matplotlib,Python中使用代理艺术家的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码段:

fig2 = plt.figure(figsize=(8,6))
ax1 = fig2.add_subplot(111)
ax1.scatter((logngal),(logm200),c='r',label='$0.0<z<1.0$')
ax1.plot((logngal),(curve_y_1),'y',linewidth=2,label='$slope=%s \pm %s$'%(slope1,slope1_err))


ax1.fill_between(x_pred, lower, upper, color='#888888', alpha=0.5)
p1 = mpatches.Rectangle((0, 0), 1, 1, fc="#888888",alpha=0.5)
ax1.legend([p1],['$1\sigma\/confidence\/limts$'])

fig2.show()

执行上述操作时,我只看到图例中提到的$1\sigma\/confidence\/limts$.

When I perform the above, I only see $1\sigma\/confidence\/limts$ mentioned in the legend.

正如您所看到的,我也分别在ax1.scatterax1.plot中分别调用label='$0.0<z<1.0$'label='$slope=%s \pm %s$'%(slope1,slope1_err).

Whereas as you can see that I also call label='$0.0<z<1.0$' and label='$slope=%s \pm %s$'%(slope1,slope1_err) in ax1.scatter and ax1.plot respectively.

这不会在图例中显示.

This does not get plotted in the legend.

如何在图例中添加以上所有三个标签?

推荐答案

在绘制它们时,您需要抓住scatterplot艺术家,然后将它们的手柄和标签提供给legend.例如,这是对您的代码进行了修改(在开始时添加了一些示例数据只是为了使其运行):

you need to grab the scatter and plot artists as you plot them, and then feed the handles and labels from them to legend. For example, here's your code modified (with some sample data at the beginning just to get it to run):

plt.plot返回一个Line2D对象的列表,因此,如果将其读取为pplot, = plt.plot(...),则会解压缩该单项列表.

plt.plot returns a list of Line2D objects, so if you read it as pplot, = plt.plot(...), you unpack that one-item list.

然后可以在pplotpscat上使用.get_label()给图例添加标签.

You can then use .get_label() on pplot and pscat to give the labels to the legend.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches

# Some things to make your script run when I don't have your data
slope1,slope1_err='this','that'
logngal   = np.linspace(0,1,20)
logm200   = np.random.rand(20)
x_pred    = np.linspace(0,1,20)
curve_y_1 = 0.5*(np.sin(logngal)/2.+np.cos(logngal))
upper     = np.sin(x_pred)/2.
lower     = np.cos(x_pred)
# end of sample data

fig2 = plt.figure(figsize=(8,6))
ax1 = fig2.add_subplot(111)

pscat  = ax1.scatter((logngal),(logm200), c='r',label='$0.0<z<1.0$')
pplot, = ax1.plot((logngal),(curve_y_1),'y',linewidth=2,label='$slope=%s \pm %s$'%(slope1,slope1_err))

ax1.fill_between(x_pred, lower, upper,color='#888888', alpha=0.5)

p1 = mpatches.Rectangle((0, 0), 1, 1, fc="#888888",alpha=0.5)

handles = [p1,pplot,pscat]
labels  = ['$1\sigma\/confidence\/limts$',pplot.get_label(),pscat.get_label()]

ax1.legend(handles,labels)

fig2.show()

这篇关于在图例,matplotlib,Python中使用代理艺术家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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