3

I tried to get the legend right for the dashed line so I played with the rcParams a little bit, but it for some reasons wouldn't work on my computer.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.rcParams['legend.numpoints'] = 5
matplotlib.rcParams['legend.scatterpoints'] = 5


fig, axs = plt.subplots()
axs.plot(range(10), '--k', label="line")
axs.plot(range(10), range(10)[::-1], ':k', label="scatter")
axs.legend(loc=9)

plt.show()

And the resultant figure is: Problematic legend

And as can be seen, the numpoints for the dashed line is not enough. Would anyone please help?

Thanks!

Yuxiang Wang
  • 8,095
  • 13
  • 64
  • 95

1 Answers1

4

If you make a plot with markers, matplotlib.rcParams['legend.numpoints'] adjust the number of points drawn on the legend lines.

If you substitute your plot by these:

axs.plot(range(10), '--k', label="line", marker='d')
axs.plot(range(10), range(10)[::-1], ':k', label="scatter", marker='o')

you get this image:enter image description here

I don't know what does matplotlib.rcParams['legend.scatterpoints'] do, but I guess regulates the number of points in the legend of scatter plots.

If you want to change the length of the lines in the legend give a try with matplotlib.rcParams['legend.handlelength'] and/or matplotlib.rcParams['legend.handleheight']. More info about rc file can be found here

As suggested by @tcaswell, you don't have to set rc parameters. All the legend.* parameters are available as keywords for the legend function. See matplotlib.pyplot.legend documentation

Francesco Montesano
  • 8,485
  • 2
  • 40
  • 64
  • 2
    `Line2D` objects and `scatter` objects are handled differently by the legend code., `numpoints` sets the number of markers that are shown for `Line2D` objects, `scatterpoints` sets the same for scatter plots. – tacaswell Oct 22 '13 at 22:34
  • 2
    and you don't need to use `rcparams` to control this, just pass them as keyword arguments to `legend`. – tacaswell Oct 22 '13 at 22:35
  • @tcaswell: thank for confirming the `scatterpoints`. later I'll edit the answer adding the fact that you can use `legend` keywords – Francesco Montesano Oct 23 '13 at 05:29