gpt4 book ai didi

python - 图例在 matplotlib 中使用 PathCollections

转载 作者:太空狗 更新时间:2023-10-30 02:32:43 25 4
gpt4 key购买 nike

我正在使用集合绘制圆圈组,但我无法生成这三个类别的图例。我要:

  • 类别 1:红色圆圈
  • Cat 2:蓝色圆圈
  • 类别 3:黄色圆圈
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Circle
import numpy as np

# (modified from one of the matplotlib gallery examples)
resolution = 50 # the number of vertices
N = 50
Na = 25
Nb = 10
x = np.random.random(N)
y = np.random.random(N)
radii = 0.1*np.random.random(30)

xa = np.random.random(Na)
ya = np.random.random(Na)
radiia = 0.1*np.random.random(50)


xb = np.random.random(Nb)
yb = np.random.random(Nb)
radiib = 0.1*np.random.random(60)

patches = []
patchesa = []
patchesb = []
for x1,y1,r in zip(x, y, radii):
circle = Circle((x1,y1), r)
patches.append(circle)

for x1,y1,r in zip(xa, ya, radiia):
circle = Circle((x1,y1), r)
patchesa.append(circle)

for x1,y1,r in zip(xb, yb, radiib):
circle = Circle((x1,y1), r)
patchesb.append(circle)


fig = plt.figure()
ax = fig.add_subplot(111)

colors = 100*np.random.random(N)
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4, label= "Cat 1", facecolor="red")
pa = PatchCollection(patchesa, cmap=matplotlib.cm.jet, alpha=0.3, label= "Cat 2", facecolor="blue")
pb = PatchCollection(patchesb, cmap=matplotlib.cm.jet, alpha=0.4, label= "Cat 3", facecolor="yellow")
#p.set_array(colors)
ax.add_collection(p)
ax.add_collection(pa)
ax.add_collection(pb)
ax.legend(loc = 2)
plt.colorbar(p)

print p.get_label()

plt.show()

PathCollection 不是可迭代对象,因此尝试通过以下方式生成图例;

legend([p, pa, pb], ["cat 1", "2 cat", "cat 3"])

不起作用。

标题如何出现?

我的系统在 Python 2.7 和 Matplotlib 1.2.0_1 上运行

请注意,命令 print p.get_label() 显示对象具有关联的标签,但 matplotlib 无法挂载图例。

最佳答案

一种可能的解决方案是添加 Line2D 对象以在图例中使用,也称为使用代理艺术家。为此,您必须将 from matplotlib.lines import Line2D 添加到您的脚本中,然后您可以替换此代码:

ax.legend(loc = 2)
plt.colorbar(p)

print p.get_label()

用这个:

circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="red")
circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.3, markersize=10, markerfacecolor="blue")
circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="yellow")

plt.legend((circ1, circ2, circ3), ("Cat 1", "Cat 2", "Cat 3"), numpoints=1, loc="best")

enter image description here

关于python - 图例在 matplotlib 中使用 PathCollections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16614558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com