Skip to main content
 首页 » 编程设计

Python,matplotlib之基于条件变量的图例 -

2024年10月24日11davidwang456

我有一个数据,可以用在散点图中。

我也有相同数据的标签。所以我正在使用条件着色:

# import needed things 
fig = plt.figure() 
r = fig.add_subplot(121) 
r.scatter(np.arange(500), X[ :500, 0] c = Y[:500] 
# x and y labels set here 
 
g = fig.add_subplot(122) 
g.scatter(np.arange(500), X[ :500, 1] c = Y[:500] 
# x and y labels set here 
 
plt.show()     

我还需要一个图例,提示哪种类型有哪种颜色。我试过这个:

plt.legend((r, g), ("one", "zero"), scatterpoints = 1, loc = "upper left") 

但是我收到警告

.../site-packages/matplotlib/legend.py:633: UserWarning: Legend does not support <matplotlib.axes._subplots.AxesSubplot object at 0x7fe37f460668> instances. 
A proxy artist may be used instead. 

并且不显示图例。

请您参考如下方法:

我可以通过替换来运行你的代码

r.scatter(np.arange(500), np.arange(500), c= np.arange(500)) 
g.scatter(np.arange(500), np.arange(500), c= np.arange(500)) 

我遇到了一个类似的错误,将我指向 matplotlib.org 上的一个页面,见下文:

/Users/sdurant/anaconda/lib/python2.7/site-packages/matplotlib/legend.py:611: UserWarning: Legend 不支持实例。 可以改用代理艺术家。 请参阅:http://matplotlib.org/users/legend_guide.html#using-proxy-artist “#using-proxy-artist”.format(orig_handle))

我不太明白您希望您的图例看起来像什么,但该页面有几种类型的示例,希望对您有所帮助。

编辑:这更有意义,这就是您正在寻找的大致内容吗?

import matplotlib.patches as mpatches 
import matplotlib.pyplot as plt 
 
red_patch = mpatches.Patch(color='red', label='one') 
blue_patch = mpatches.Patch(color='blue', label='zero') 
 
area = np.pi *30 
fig = plt.figure() 
r = fig.add_subplot(121) 
r.scatter(np.arange(10), np.arange(10), c= [random.randint(2) for k in range(10)], s=area) 
# x and y labels set here 
plt.legend(handles=[red_patch,blue_patch]) 
g = fig.add_subplot(122) 
g.scatter(np.arange(10), np.arange(10), c= [random.randint(2) for k in range(10)], s=area) 
# x and y labels set here 
 
plt.legend(handles=[red_patch,blue_patch])