How to change fonts in matplotlib (python)?

后端 未结 5 1136
不思量自难忘°
不思量自难忘° 2020-11-29 20:26

It sounds as an easy problem but I do not find any effective solution to change the font (not the font size) in a plot made with matplotlib in python.

I found a coup

5条回答
  •  隐瞒了意图╮
    2020-11-29 20:47

    The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):

    import os
    from matplotlib import font_manager as fm, rcParams
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
    prop = fm.FontProperties(fname=fpath)
    fname = os.path.split(fpath)[1]
    ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
    ax.set_xlabel('This is the default font')
    
    plt.show()
    

    print(fpath) will show you where you should put the .ttf.

    You can see the output here: https://matplotlib.org/gallery/api/font_file.html

提交回复
热议问题