在图例中将Matplotlib矩形更改为圆形

时间:2014-09-05 15:04:05

标签: python matplotlib

考虑以下绘图代码:

plt.figure(figsize=(10,6))
for k in range(nruns):
    plt.plot(Thing1['Data'][:,k],color='Grey',alpha=0.10)
plt.plot(Thing2[:,1],Thing2[:,4],'ko')
a = plt.Rectangle((0, 0), 1, 1, fc="Grey",alpha=0.50)
b = plt.Rectangle((0, 0), 1, 1, fc="Black", alpha=1.00)
plt.legend([a,b], ["Thing1","Thing2"],loc=2,fontsize='small')
plt.xlabel("Time",fontsize=16)
plt.ylabel("Hijinks",fontsize=16)
plt.show()

我真的很喜欢" b"是一个圆圈,而不是一个矩形。但我对matplotlib代码非常可怕,尤其是代理艺术家的使用。有没有机会直截了当地做到这一点?

2 个答案:

答案 0 :(得分:2)

使用较新版本的matplotlib可以更轻松地完成此操作。

from pylab import *

p1 = Rectangle((0, 0), 1, 1, fc="r")
p2 = Circle((0, 0), fc="b")
p3 = plot([10,20],'g--')
legend([p1,p2,p3], ["Red Rectangle","Blue Circle","Green-dash"])

show()

请注意,这不是我的工作。这是从Matplotlib, legend with multiple different markers with one label获得的。

答案 1 :(得分:1)

你非常接近。您只需要使用Line2D艺术家并将其属性设置为ususal:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,6))

fakexy = (0, 0)
a = plt.Rectangle(fakexy, 1, 1, fc="Grey",alpha=0.50)
b = plt.Line2D(fakexy, fakexy, linestyle='none', marker='o', markerfacecolor="Black", alpha=1.00)

ax.legend([a, b], ["Thing1", "Thing2"], loc='upper left', fontsize='small')
ax.set_xlabel("Time", fontsize=16)
ax.set_ylabel("Hijinks", fontsize=16)

我明白了:

enter image description here

相关问题