我試圖通過定義一個全局函數按照給定的步驟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? –