Matplotlib使记号标签字体变小

2024-04-26 03:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在matplotlib图中,如何使用ax1.set_xticklabels()减小记号标签的字体大小

此外,如何将其从水平旋转到垂直


Tags: matplotlib水平标签字体大小setax1记号xticklabels
3条回答

其实还有一个更简单的方法。我刚刚发现:

import matplotlib.pyplot as plt
# We prepare the plot  
fig, ax = plt.subplots()

# We change the fontsize of minor ticks label 
ax.tick_params(axis='both', which='major', labelsize=10)
ax.tick_params(axis='both', which='minor', labelsize=8)

不过,这只回答了您问题中label部分的大小

请注意,较新版本的MPL有用于此任务的快捷方式。这个问题的另一个答案中显示了一个例子:https://stackoverflow.com/a/11386056/42346

下面的代码用于说明目的,不一定要优化

import matplotlib.pyplot as plt
import numpy as np

def xticklabels_example():
    fig = plt.figure() 

    x = np.arange(20)
    y1 = np.cos(x)
    y2 = (x**2)
    y3 = (x**3)
    yn = (y1,y2,y3)
    COLORS = ('b','g','k')

    for i,y in enumerate(yn):
        ax = fig.add_subplot(len(yn),1,i+1)

        ax.plot(x, y, ls='solid', color=COLORS[i]) 

        if i != len(yn) - 1:
            # all but last 
            ax.set_xticklabels( () )
        else:
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(14) 
                # specify integer or one of preset strings, e.g.
                #tick.label.set_fontsize('x-small') 
                tick.label.set_rotation('vertical')

    fig.suptitle('Matplotlib xticklabels Example')
    plt.show()

if __name__ == '__main__':
    xticklabels_example()

enter image description here

要同时指定字体大小和旋转,请尝试以下操作:

plt.xticks(fontsize=14, rotation=90)

相关问题 更多 >