首页 文章

如何在Matplotlib中设置图 Headers 和轴标签字体大小?

提问于
浏览
336

我正在Matplotlib中创建一个像这样的人物:

from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

我想指定图 Headers 和轴标签的字体大小 . 我需要三个不同的字体大小,所以设置全局字体大小( mpl.rcParams['font.size']=x )不是我想要的 . 如何单独设置图 Headers 和轴标签的字体大小?

4 回答

  • 20

    处理 labeltitle 等文本的函数接受与matplotlib.text.Text相同的参数 . 对于字体大小,您可以使用 size/fontsize

    from matplotlib import pyplot as plt    
    
    fig = plt.figure()
    plt.plot(data)
    fig.suptitle('test title', fontsize=20)
    plt.xlabel('xlabel', fontsize=18)
    plt.ylabel('ylabel', fontsize=16)
    fig.savefig('test.jpg')
    

    对于全局设置 titlelabel 尺寸,mpl.rcParams包含 axes.titlesizeaxes.labelsize . (来自页面):

    axes.titlesize      : large   # fontsize of the axes title
    axes.labelsize      : medium  # fontsize of the x any y labels
    

    (据我所知,没有办法单独设置 xy 标签尺寸 . )

    而且我看到 axes.titlesize 不会影响 suptitle . 我想,你需要手动设置 .

  • 0

    您也可以通过rcParams字典全局执行此操作:

    import matplotlib.pylab as pylab
    params = {'legend.fontsize': 'x-large',
              'figure.figsize': (15, 5),
             'axes.labelsize': 'x-large',
             'axes.titlesize':'x-large',
             'xtick.labelsize':'x-large',
             'ytick.labelsize':'x-large'}
    pylab.rcParams.update(params)
    
  • 49

    如果您更习惯使用 ax 对象进行绘图,您可能会发现 ax.xaxis.label.set_size() 更容易记住,或者至少更容易使用ipython终端中的tab找到 . 看来效果似乎需要重绘操作 . 例如:

    import matplotlib.pyplot as plt
    
    # set up a plot with dummy data
    fig, ax = plt.subplots()
    x = [0, 1, 2]
    y = [0, 3, 9]
    ax.plot(x,y)
    
    # title and labels, setting initial sizes
    fig.suptitle('test title', fontsize=12)
    ax.set_xlabel('xlabel', fontsize=10)
    ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']
    
    # setting label sizes after creation
    ax.xaxis.label.set_size(20)
    plt.draw()
    

    我不知道在创建之后设置suptitle大小的类似方法 .

  • 501

    要仅修改 Headers 的字体(而不是轴的字体),我使用了这个:

    import matplotlib.pyplot as plt
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
    

    除了来自matplotlib.text.Text的所有kwargs之外的fontdict .

相关问题