刻度指的是轴上数据点的标记,Matplotlib会自动将刻度绘制在x轴和y轴上。这个功能是由Matplotlib内置的校准定位器和formator(两个内置类)实现的。
在大多数情况下,这两个内置类完全可以满足我们的绘图需求。然而,在某些情况下,刻度标签或刻度需要满足特定的要求,例如将刻度设置为 "英文数字 "或 "大写阿拉伯数字",就需要对它们进行重置。
1.如何设置Matplotlib绘图的刻度和刻度标签
-
**set_xticks()和set_yticks()**函数接受一个列表对象作为参数,列表中的元素代表要在相应坐标轴上显示的刻度。
-
例如ax.set_xticks([2,4,6,8,10]) 将以2,4,6,8,10的标记设置X轴刻度。
-
你还可以分别使用**set_xticklabels()和set_yticklabels()**函数设置与刻度线对应的刻度标签。
-
下面是示例的源代码:
import matplotlib.pyplot as plt import numpy as np def set_matplotlib_scale_and_label_example(): # create the x-axis value array. x_value = np.arange(0, 10, 0.01) # calculate the y-axis value array. y_value = np.sin(x_value) # create the figure object. fig = plt.figure() # add the drawing area. ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # plot the sine curve figure. ax.plot(x_value, y_value) # set the curve figure title. ax.set_title('sine curve') # set the x-axis label. ax.set_xlabel('angle') # set the x-axis scale value. ax.set_xticks([0,1,2,3,4,5,6,7,8,9]) # set the x-axis scale label. ax.set_xticklabels(['zero','one','two','three','four','five','six','seven','eight','nine']) # set the y-axis scale value. ax.set_yticks([-3, -2, -1, 0, 1, 2, 3]) # set the y-axis scale label. ax.set_yticklabels(['-three', '-two', '-one', 'zero', 'one', 'two', 'three']) # show the plot. plt.show() if __name__ == '__main__': set_matplotlib_scale_and_label_example() -
下面是上述源代码生成的图