matplotlib绘制图表----设置坐标轴刻度显示(一)

在上一篇文章中,我们介绍了一个小案例,在那个案例中,我们可以大致了解到matplotlib的基础用法。在这篇文章中,我们会更深入的讲解matplotlib更多用法。

设置坐标轴刻度

设置坐标轴的范围

我们通常使用axis()来设置x轴、y轴的刻度范围。axis()待传人的参数分别为xmin, xmax, ymin, ymax。我们也可以使用xlim()ylim()来设置范围

import matplotlib.pyplot as plt

x = [i for i in range(4)]
y = [5, 4 , 9, 8]

plt.figure()

plt.axis([-1, 7, -1, 10])
plt.plot(x, y)

plt.show()

设置坐标轴刻度

刻度定位器(tick locator):指定刻度所在的位置

扫描二维码关注公众号,回复: 11368978 查看本文章

刻度格式器(tick formatter):指定刻度显示的样式

刻度分为主刻度(major ticks)和次刻度(minor ticks)。主刻度和次刻度可以被独立地指定位置和格式化。

matplotlib.pyplot.locator_params()可以控制刻度定位器的行为

设置主定位器,倍数为10

ax = gca()

ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10))


import matplotlib.pyplot as plt

from matplotlib.pyplot import MultipleLocator

#从pyplot导入MultipleLocator类,这个类用于设置刻度间隔

 

x_values=list(range(11))

y_values=[x**2 for x in x_values]

plt.plot(x_values,y_values,c='green')

plt.title('Squares',fontsize=24)

plt.tick_params(axis='both',which='major',labelsize=14)

plt.xlabel('Numbers',fontsize=14)

plt.ylabel('Squares',fontsize=14)

x_major_locator=MultipleLocator(1)

#把x轴的刻度间隔设置为1,并存在变量里

y_major_locator=MultipleLocator(10)

#把y轴的刻度间隔设置为10,并存在变量里

ax=plt.gca()

#ax为两条坐标轴的实例

ax.xaxis.set_major_locator(x_major_locator)

#把x轴的主刻度设置为1的倍数

ax.yaxis.set_major_locator(y_major_locator)

#把y轴的主刻度设置为10的倍数

plt.xlim(-0.5,11)

#把x轴的刻度范围设置为-0.5到11,因为0.5不满一个刻度间隔,所以数字不会显示出来,但是能看到一点空白

plt.ylim(-5,110)

#把y轴的刻度范围设置为-5到110,同理,-5不会标出来,但是能看到一点空白

plt.show()

实验部分参考:https://blog.csdn.net/weixin_44520259/article/details/89917026

猜你喜欢

转载自blog.csdn.net/Stybill_LV_/article/details/106393435
今日推荐