【问题标题】:How to set matplotlib font for title, axes,如何为标题、轴设置 matplotlib 字体,
【发布时间】:2014-09-01 23:52:33
【问题描述】:

我不知道如何更改字体,让我们说“times”。我的尝试不起作用。

import numpy as np
import matplotlib.pyplot as plt

x     = np.array([0, 75, 150])
y     = np.array([0, 1, 3])
coeff = np.polyfit(x, y, 2)

xx = np.linspace(0, 150, 150)
yy = coeff[0] * xx**2 + coeff[1] * xx + coeff[2]

plt.title(unicode("Correction factor", "utf-8"),fontname="times")
plt.xlabel(unicode("Temperature in °C", "utf-8"))
plt.ylabel(unicode("fKorr", "utf-8"))
plt.plot(xx,yy)
plt.show()

编辑:它适用于“Times New Roman”。我使用的其他程序知道“时间”。

【问题讨论】:

  • 运行代码时会发生什么? unicode("Correction factor, "utf-8"),fontname="times") 行的语法不正确,应该是unicode("Correction factor", "utf-8"),fontname="times")

标签: python matplotlib


【解决方案1】:

根据平台的不同,Times New Roman字体的名称可以不同,比如我现在的机器,Mac OS

import matplotlib.font_manager as fmg
for i, item in enumerate(fmg.findSystemFonts()):
    try:
        name=fmg.FontProperties(fname=item).get_name()
        if 'TIMES' in name.upper():
            print name, item, i
    except:
        pass

#Times New Roman /Library/Fonts/Times New Roman Italic.ttf 223
#Times New Roman /Library/Fonts/Times New Roman Bold Italic.ttf 232
#Times New Roman /Library/Fonts/Times New Roman Bold.ttf 336
#Times New Roman /Library/Fonts/Times New Roman.ttf 367

我认为这个解决方案可能更安全:直接提供字体文件的路径。 matplotlib.font_manager.findSystemFonts() 将列出每个文件的路径:

x     = np.array([0, 75, 150])
y     = np.array([0, 1, 3])
coeff = np.polyfit(x, y, 2)

xx = np.linspace(0, 150, 150)
yy = coeff[0] * xx**2 + coeff[1] * xx + coeff[2]

all_font = fmg.findSystemFonts()
fontprop = fmg.FontProperties(fname=all_font[223]) #you may have a different index
plt.title(unicode("Correction factor", "utf-8"), fontproperties=fontprop)
fontprop = fmg.FontProperties(fname=all_font[232])
plt.xlabel(unicode("Temperature in °C", "utf-8"), fontproperties=fontprop)
fontprop = fmg.FontProperties(fname=all_font[236])
plt.ylabel(unicode("fKorr", "utf-8"), fontproperties=fontprop)
plt.plot(xx,yy)

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 2012-09-08
    • 2015-05-30
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多