【问题标题】:Python, matplotlib - legend based on a conditional variable -Python,matplotlib - 基于条件变量的图例 -
【发布时间】:2016-02-10 11:07:10
【问题描述】:

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

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

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

并且不显示图例。

【问题讨论】:

标签: python matplotlib scatter-plot


【解决方案1】:

我能够通过替换来运行您的代码

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

【讨论】:

  • 这肯定行得通。我的Y[:500] 包含每个类的标签。只有 2 个标签。所以传奇会有两个条目。 red dot - one, blue dot - zero。所以本质上问题还没有解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 2020-08-01
  • 1970-01-01
相关资源
最近更新 更多