Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: ensuring full dash pattern appears in legend

Tags:

matplotlib

Consider this simple example:

#setup figure
import matplotlib.pyplot as plt
import pylab
import math
import numpy as np
#output control
fig_width_pt = 345.0 # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inch
golden_mean = (math.sqrt(5)-1.0)/2.0         # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt  # width in inches
fig_height = fig_width*golden_mean      # height in inches
fig_size =  [fig_width,fig_height]
params = {'backend': 'ps',
      'axes.labelsize': 10,
      'text.fontsize': 10,
      'legend.fontsize': 8,
      'xtick.labelsize': 8,
      'ytick.labelsize': 8,
      'text.usetex': True,
      'figure.figsize': fig_size,
      'figure.dpi': 1000,
      'savefig.dpi': 1000}
pylab.rcParams.update(params)

plt.figure().add_subplot(1,1,1)   
#plot some lines
dashes = [(None, None), [2, 2], [7, 4, 3, 4]]
titles = ["really long title one", "long title the second", "an even longer title, am I right?"]

for i in range(3):
    x = np.arange(i, i + np.pi/2.0, 0.01)
    y = np.sin(x) + i
    line,= plt.plot(x, y, label = titles[i])
    line.set_dashes(dashes[i])

plt.legend()
plt.show()

Running this simple program with 'legend.fontsize': 8 produces this. Note that the dash style for the dot-dash line (the third in the legend) is very difficult to interpret. If you zoom in, you'll see the tiny black dot shows that it corresponds to the figure, but this is hardly ideal.

I have been able to fix this by changing the legend fontsize to ten, resulting in this, but this is too large for my actual figure.

Any thoughts on how I can ensure that the full linestyle/dashstyle is displayed?

like image 484
arghdos Avatar asked Jun 17 '14 18:06

arghdos


1 Answers

You can change the length of the lines in the legend (without changing the font) by setting the handlelength keyword. Try

plt.legend(handlelength=3)
like image 98
Ajean Avatar answered Oct 27 '22 00:10

Ajean