3

I am trying to change the font of the legend by defining a global function following steps given here. The code used is:

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

path = 'palatino-regular.ttf'
prop = font_manager.FontProperties(fname=path)

def change_matplotlib_font():
    figures = [x for x in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
    for figure in figures:
        for ax in figure.canvas.figure.get_axes():
            ax.legend(prop = prop)
            for label in ax.get_xticklabels():
                label.set_fontproperties(prop)
            for label in ax.get_yticklabels():
                label.set_fontproperties(prop)


m = 5
n = 5

x = np.zeros(shape=(m, n))
plt.figure(figsize=(5.15, 5.15))
plt.clf()
plt.subplot(111)
marker = itertools.cycle(('o', 'v', '^', '<', '>', 's', '8', 'p'))
ax = plt.gca()
for i in range(1, n):
    x = np.dot(i, [1, 1.1, 1.2, 1.3])
    y = x ** 2
    color = next(ax._get_lines.color_cycle)
    plt.plot(x, y, linestyle='', markeredgecolor='none', marker=marker.next(), color=color, label = str(i))
    plt.plot(x, y, linestyle='-', color = color)
plt.ylabel(r'y', labelpad=6)
plt.xlabel(r'x', labelpad=6)
# change_matplotlib_font()
plt.legend(loc = 'center left', bbox_to_anchor = (1.025, 0.5))
change_matplotlib_font()
plt.savefig('tick_font.pdf', bbox_inches='tight')

When I don't invoke the function change_matplotlib_font I get this output (no change in font):

enter image description here

When I invoke the function the font changes but the location also changes:

enter image description here

How can I change the font preserving the location provided before invoking the function in Python?

Community
  • 1
  • 1
Tom Kurushingal
  • 6,086
  • 20
  • 54
  • 86
  • 1
    Why are you embedding the code in your `change_matplotlib_font` function? And why are you doing `figures = [x for x in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] ` in there? It seems that is adding more complexity and having the undesired result of altering your legend location for you. It seems like @cphlewis addresses how to change legend font, but your actual question is how to change axis label and legend font without moving the legend - is that right? And are you trying to do this on multiple plots? – J Richard Snape Aug 10 '15 at 09:38
  • Yes, I change the axis tick fonts using the function for multiple fonts, and I am trying to change the legend font only without moving it. – Tom Kurushingal Aug 10 '15 at 12:00
  • I can see what your code does - I'm asking why - in order to get at the underlying question. Mainly - why are you creating a list of all figures in this way, when you have only one? The method you are using is lifted from a question that's dealing with a different circumstance - I can't see why you don't just include @cphlewis syntas in your (already existing) call to `plt.legend()` ? – J Richard Snape Aug 10 '15 at 12:10

1 Answers1

7

Just pass the font-prop-dict to legend() directly, as the legend docstring suggests. Combining the matplotlib gallery legend example with your legend-on-the-side, specifying location and font properties at once:

legend = plt.legend(loc = 'center left', 
                    bbox_to_anchor = (1.025,    0.5),
                    shadow=True,
                    prop={'family':'cursive','weight':'roman','size':'xx-large'})

gets this result with the fonts I have installed:

enter image description here

cphlewis
  • 15,759
  • 4
  • 46
  • 55
  • I did the same by placing it in the function change_matplotlib_font, but the location I set before is overriden. How do I preserve the location and change only on the font. – Tom Kurushingal Aug 10 '15 at 06:49
  • This example preserves the location and changes the font. – cphlewis Aug 10 '15 at 18:01
  • I can't figure out what your actual use case is -- if you get a new font definition after making a plot, the easiest way to change the legend is to make the exact same `legend()` call again (with the prop dictionary it points to altered). – cphlewis Aug 10 '15 at 18:06