I am unable to make the legend of my Matplotlib v. 2.0.2 figure appear in Python 2.7. I have a minimal example below which draws arrows on an axis in a for loop.
Since assigning the label keyword definition every iteration didn't work to make the legend appear, I am trying to use a conditional to set the label during the first iteration only.
Trying the "bbox_to_anchor" and "loc" arguments in ax.legend( ) had no effect, so I am leaving out any legend arguments.
Anyone have any ideas how to make a legend appear which shows the "Arrow1" and "Arrow2" labels with red and black arrow markers, respectively, next to the labels?
minimal example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots( )
ax.set_xlim( 0, 11 )
ax.set_ylim( 0, 2 )
kwargs1 ={'color':'r'}
kwargs2 ={'color':'black'}
for i in range(1, 11):
ax.arrow( i-0.2, 0, 0, i/10., width=0.1,
label='Arrow1' if i == 1 else None, **kwargs1 )
ax.arrow( i+0.2, 0, 0, i/10., width=0.1,
label='Arrow2' if i == 1 else None, **kwargs2 )
ax.legend( )
See link to picture of output plot with no legend:
EDIT:
It seems setting the label definition every iteration is OK. Here's a solution that shows line markers with the correct colors and labels in a legend:
import matplotlib.pyplot as plt
fig, ax = plt.subplots( )
ax.set_xlim( 0, 11 )
ax.set_ylim( 0, 2 )
kwargs1 ={'color':'r' }
kwargs2 ={'color':'black'}
for i in range(1, 11):
Arrow1 = ax.arrow( i-0.2, 0, 0, i/10., width=0.1,
label='Arrow1', **kwargs1 )
Arrow2 = ax.arrow( i+0.2, 0, 0, i/10., width=0.1,
label='Arrow2', **kwargs2 )
ax.legend( handles=[Arrow1, Arrow2] )
Picture of plot output with legend:
Another Edit:
For reasons that I don't think I'll get to the bottom of, the complexity of my actual script (not the minimal example) required an invisible "Proxy Artist" for adding labels to the legend. This was suggested in these docs for unsupported artists, here
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots( )
ax.set_xlim( 0, 11 )
ax.set_ylim( 0, 2 )
kwargs1 ={'color':'red' }
kwargs2 ={'color':'black'}
for i in range(1, 11):
ax.arrow( i-0.2, 0, 0, i/10., width=0.1, **kwargs1 )
Arrow1 = Rectangle((0, 0), 1, 1, label='Arrow1', fc='red')
ax.arrow( i+0.2, 0, 0, i/10., width=0.1, **kwargs2 )
Arrow2 = Rectangle((0, 0), 1, 1, label='Arrow2', fc='black')
ax.legend( handles=[Arrow1, Arrow2], loc='upper left' )