[Matplotlib-users] Legend labels and placement ignored?

Akkana Peck akkana at shallowsky.com
Fri Feb 23 16:01:35 EST 2018


Hi -- I'm having a problem with the legend on one of two subplots.
For each curve plotted on each subplot, I set label="something",
and then I set subplot.legend(position). This works for ax2, but
for ax1 it's ignored.

I asked on #matplotlib on Freenode and was advised it looked like
a bug and that I should report it. So I did,
https://github.com/matplotlib/matplotlib/issues/10576
but I thought I'd ask here too, to see if I'm doing something wrong
in the way I specify my legends.

I pared the example program down to this:

=======
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np

def plot_planet():
    tde = np.array([-23.029638, -22.953653, -22.871279, -22.782548, -22.687498, -22.586167, -22.478597, -22.364832, -22.244918, -22.118904, -21.986842])

    obliq_ra = [-3.67878, -3.97686, -4.27044, -4.55928, -4.84302, -5.12142, -5.39412, -5.66088, -5.92146, -6.17544, -6.42264]
    eccen_ra = [ 0.40722, 0.27366, 0.14028, 0.0072, -0.12558, -0.25788, -0.3897, -0.52098, -0.6516, -0.78162, -0.91086]
    true_ra = [-3.27156, -3.7032, -4.13016, -4.55208, -4.9686, -5.3793, -5.78382, -6.18186, -6.57306, -6.95706, -7.3335 ]

    fig = plt.figure(figsize=(12, 8))   # width, height in inches

    gs = gridspec.GridSpec(1, 2, width_ratios=[2.5, 1])

    # Plot equations of time:
    ax1 = fig.add_subplot(gs[0])
    ax1.plot(obliq_ra, label="obliquity",    color="lightblue")
    ax1.plot(eccen_ra, label="eccentricity", color="pink")
    ax1.plot(true_ra,  label="Eqn of Time",  color="black")
    ax1.set_title("Equation of Time")
    ax1.legend("upper left")

    # Plot the analemma:
    ax2 = fig.add_subplot(gs[-1])
    ax2.plot(obliq_ra, tde, label="obliquity", color="lightblue")
    ax2.plot(eccen_ra, tde, label="eccentricity", color="pink")
    ax2.plot(true_ra,  tde, label="analemma", color="black")
    ax2.set_title("Analemma")
    ax2.legend(loc="upper right")

    plt.show()

if __name__ == '__main__':
    plot_planet()
=======

Here's what I see: http://shallowsky.com/tmp/mpl-legend.jpg
Note that the left subplot (ax1) has the legend in the upper right
even though I specified upper left, and that the labels are
mysteriously u, p, and p -- I can't figure out where those labels
are coming from but they're clearly not the ones I specified.

Any idea how I could fix this? Thanks!

        ...Akkana


More information about the Matplotlib-users mailing list