3

Consider the following plotting code:

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

I'd really like "b" to be a circle, rather than a rectangle. But I'm rather horrid at matplotlib code, and especially the use of proxy artists. Any chance there's a straightforward way to do this?

Fomite
  • 2,213
  • 7
  • 30
  • 46

2 Answers2

3

You're very close. You just need to use a Line2D artist and set its properties like 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)

I get:

enter image description here

Paul H
  • 65,268
  • 20
  • 159
  • 136
2

There is a much easier way to do this with newer versions of 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()

Note this is not my work. This is obtained from Matplotlib, legend with multiple different markers with one label.

Community
  • 1
  • 1
PhysicalChemist
  • 540
  • 4
  • 14