如何更改图例字体而不影响matplotlib中的其他参数?

时间:2015-08-09 13:44:08

标签: python matplotlib fonts

我试图通过在给定here的步骤之后定义全局函数来更改图例的字体。使用的代码是:

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')

当我没有调用函数change_matplotlib_font时,我得到了这个输出(字体没有变化):

enter image description here

当我调用该函数时,字体会发生变化但位置也会发生变化:

enter image description here

如何在Python中调用函数之前更改保留所提供位置的字体?

1 个答案:

答案 0 :(得分:6)

直接将font-prop-dict传递给legend(),正如legend文档字符串所示。将matplotlib gallery legend example与您的图例组合在一起,一次指定位置和字体属性:

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

使用我安装的字体获得此结果:

enter image description here