2015-08-09 57 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

相关问题