Customizing legend in matplotlib

mvd

i'm plotting rectangles that have different colors in matplotlib. i would like each type of rectangle to have a single label that appears once in the legend. my code is:

import matplotlib.patches as patches
fig1 = plt.figure()
ax = plt.subplot(1,1,1)
times = [0, 1, 2, 3, 4]
for t in times:
    if t % 2 == 0:
        color="blue"
    else:
        color="green"
    ax.add_patch(patches.Rectangle((t, 0.5), 0.1, 0.1,
                                   facecolor=color,
                                   label=color))
plt.xlim(times[0], times[-1] + 0.1)
plt.legend()
plt.show()

the problem is that each rectangle appears multiple in the legend. i would like to only have two entries in the legend: a blue rectangle labeled "blue", and a green rectangle labeled "green". how can this be achieved?

Adi Levin

As documented here, you can control the legend by specifying the handles to the graphical objects for which you want the legends. In this case, two out of the five objects are needed, so you can store them in a dictionary

import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax = plt.subplot(1,1,1)
times = [0, 1, 2, 3, 4]
handle = {}
for t in times:
    if t % 2 == 0:
        color="blue"
    else:
        color="green"
    handle[color] = ax.add_patch(patches.Rectangle((t, 0.5), 0.1, 0.1,
                                   facecolor=color,
                                   label=color))
plt.xlim(times[0], times[-1] + 0.1)
print handle
plt.legend([handle['blue'],handle['green']],['MyBlue','MyGreen'])
plt.show()

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related