2015-08-09 69 views
2

我試圖通過定義一個全局函數按照給定的步驟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我得到這個輸出(在字體無變化):

enter image description here

當我調用該函數的字體變化,但位置也發生變化:

enter image description here

如何更改在調用Python中的函數之前保留提供的位置的字體?

+1

你爲什麼要嵌入你的'change_matplotlib_font'函數中的代碼?你爲什麼在那裏做'figure = [x for matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]''?這似乎增加了更多的複雜性,並導致您爲了改變傳奇位置而產生的不良後果。看起來像@ cphlewis解決了如何更改圖例字體,但實際的問題是如何在不移動圖例的情況下更改軸標籤和圖例字體 - 是嗎?你是否試圖在多個地塊上做到這一點? –

+0

是的,我使用多種字體的函數更改軸刻度字體,並且我試圖只改變圖例字體而不移動它。 –

+0

我可以看到你的代碼做了什麼 - 我在問爲什麼 - 爲了解決潛在的問題。主要是 - 你爲什麼要以這種方式創建一個所有數字的列表,當你只有一個?你正在使用的方法從一個處理不同情況的問題中解脫出來 - 我不明白爲什麼你不只是在你已經存在的對plt.legend()的調用中包含@cphlewis syntas? –

回答

6

正如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

+0

我將它放在函數change_matplotlib_font中,但我之前設置的位置被覆蓋。如何保留位置並僅更改字體。 –

+0

本示例保留位置並更改字體。 – cphlewis

+0

我無法弄清楚你的實際用例是什麼 - 如果你在繪製一個圖後得到一個新的字體定義,改變圖例的最簡單的方法就是再次調用相同的'legend()'調用道具字典它指向改變)。 – cphlewis

相關問題