大嘴巴灵机一动对《Python科学计算》的笔记(1)

大嘴巴灵机一动
大嘴巴灵机一动 (不逞口腹之欲,何以遣此有涯之生)

在读 Python科学计算

Python科学计算
  • 书名: Python科学计算
  • 作者: 张若愚
  • 页数: 621
  • 出版社: 清华大学出版社
  • 出版年: 2012-1
  • 第150页

    显示所有的中文字体:

    # -*- coding: utf-8 -*-
    from matplotlib.font_manager import fontManager
    import matplotlib.pyplot as plt
    import os
    
    fig = plt.figure(figsize=(12, 6))
    ax = fig.add_subplot(111)
    plt.subplots_adjust(0, 0, 1, 1, 0, 0)
    plt.xticks([])
    plt.yticks([])
    x, y = 0.05, 0.08
    fonts = [font.name for font in fontManager.ttflist if
             os.path.exists(font.fname) and os.stat(font.fname).st_size>1e6]
    font = set(fonts)
    dy = (1.0 - y)/(len(fonts)/4 + (len(fonts)%4 != 0))
    for font in fonts:
        t = ax.text(x, y, u'中文字体', {'fontname':font, 'fontsize':14}, transform=ax.transAxes)
        ax.text(x, y-dy/2, font, transform=ax.transAxes)
        x += 0.25
        if x >= 1.0:
            y += dy
            x = 0.05
    plt.show()

    设置中文字体: 方法一:

    from matplotlib.font_manager import FontProperties
    import matplotlib.pyplot as plt
    font = FontProperties(fname=r'C:\Windows\Fonts\simsun.ttc', size=14)
    plt.title(u'正弦波', fontproperties=font)

    方法二:

    import matplotlib.pyplot as plt
    plt.rcParams['font.family'] = 'SimHei'

    其中方法一适用于ttf和ttc字体,方法二适用于ttf字体(最上面的代码能显示出来的字体)。

    2012-09-28 16:13:15 1人喜欢 回应