我试图通过定义一个全局函数按照给定的步骤here来更改图例的字体。使用的代码是:如何更改图例字体而不影响matplotlib中的其他参数?
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我得到这个输出(在字体无变化):
当我调用该函数的字体变化,但位置也发生变化:
如何更改在调用Python中的函数之前保留提供的位置的字体?
你为什么要嵌入你的'change_matplotlib_font'函数中的代码?你为什么在那里做'figure = [x for matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]''?这似乎增加了更多的复杂性,并导致您为了改变传奇位置而产生的不良后果。看起来像@ cphlewis解决了如何更改图例字体,但实际的问题是如何在不移动图例的情况下更改轴标签和图例字体 - 是吗?你是否试图在多个地块上做到这一点? –
是的,我使用多种字体的函数更改轴刻度字体,并且我试图只改变图例字体而不移动它。 –
我可以看到你的代码做了什么 - 我在问为什么 - 为了解决潜在的问题。主要是 - 你为什么要以这种方式创建一个所有数字的列表,当你只有一个?你正在使用的方法从一个处理不同情况的问题中解脱出来 - 我不明白为什么你不只是在你已经存在的对plt.legend()的调用中包含@cphlewis syntas? –