Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change legend font only without affecting other parameters in matplotlib?

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?

like image 840
Tom Kurushingal Avatar asked Dec 05 '25 17:12

Tom Kurushingal


1 Answers

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

like image 162
cphlewis Avatar answered Dec 08 '25 07:12

cphlewis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!