matplotlib 刻度设置

本文介绍了如何使用Matplotlib设置坐标轴的主刻度和次刻度,包括刻度位置、刻度标签文本的格式设置等。通过实例展示了xticks和yticks命令的使用方法,以及如何定制刻度标签。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刻度设置

参考文档:

以xticks为例:

matplotlib.pyplot.xticks(*args, **kwargs)

获取或者设置当前刻度位置和文本的x-limits:

# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
locs, labels = xticks()

# set the locations of the xticks
xticks( arange(6) )

# set the locations and labels of the xticks
xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )

关键字 args ,如果有其他的参数则是 Text 属性。例如,旋转长的文本标注。

xticks( arange(12), calendar.month_name[1:13], rotation=17 )


设置刻度标注


相关文档:

相关文档

原型举例:

set_xticklabels(labels, fontdict=None, minor=False, **kwargs)

综合举例(1)如下:

设置指定位置的标注更改为其他的标注:

...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
          [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
          [r'$-1$', r'$0$', r'$+1$'])
...

综合举例(2)如下:

设置坐标轴主刻度和次刻度。

#!/usr/bin/env python
#-*- coding: utf-8 -*- 
#---------------------------------------------------
#演示MatPlotLib中设置坐标轴主刻度标签和次刻度标签.

#对于次刻度显示,如果要使用默认设置只要matplotlib.pyplot.minorticks_on()

#---------------------------------------------------

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

#---------------------------------------------------
xmajorLocator   = MultipleLocator(20) #将x主刻度标签设置为20的倍数
xmajorFormatter = FormatStrFormatter('%5.1f') #设置x轴标签文本的格式
xminorLocator   = MultipleLocator(5) #将x轴次刻度标签设置为5的倍数


ymajorLocator   = MultipleLocator(0.5) #将y轴主刻度标签设置为0.5的倍数
ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签文本的格式
yminorLocator   = MultipleLocator(0.1) #将此y轴次刻度标签设置为0.1的倍数

 
t = np.arange(0.0, 100.0, 1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)

ax = plt.subplot(111) #注意:一般都在ax中设置,不再plot中设置
plt.plot(t,s,'--r*')

#设置主刻度标签的位置,标签文本的格式
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_major_formatter(xmajorFormatter)

ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)

#显示次刻度标签的位置,没有标签文本
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_minor_locator(yminorLocator)

ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度

plt.show()

##########################################################

图像形式如下:

【Python <wbr>Matplotlib】设置x/y坐标轴刻度


 
Axiscontainers

matplotlib.axis.Axis对象负责刻度线、格网线、刻度标注和坐标轴标注的绘制工作。你可以设置y轴的左右刻度或者x轴的上下刻度。 Axis 也存储了用于自动调整,移动和放缩的数据和视觉间隔;同时 Locator 和Formatter 对象控制着刻度的位置以及以怎样的字符串呈现。

每一个 Axis 对象包含一个 label 属性以及主刻度和小刻度的列表。刻度是 XTick 和 YTick 对象,其包含着实际线和文本元素,分别代表刻度和注释。因为刻度是根据需要动态创建的,你应该通过获取方法get_major_ticks() 和 get_minor_ticks()以获取主刻度和小刻度的列表。尽管刻度包含了所有的元素,并且将会在下面代码中涵盖,Axis 方法包含了获取方法以返回刻度线、刻度标注和刻度位置等等:

In [285]: axis = ax.xaxis

In [286]: axis.get_ticklocs()
Out[286]: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

In [287]: axis.get_ticklabels()
Out[287]: 10 Text major ticklabel objects>

# note there are twice as many ticklines as labels because by
#  default there are tick lines at the top and bottom but only tick
#  labels below the xaxis; this can be customized
In [288]: axis.get_ticklines()
Out[288]: 20 Line2D ticklines objects>

# by default you get the major ticks back
In [291]: axis.get_ticklines()
Out[291]: 20 Line2D ticklines objects>

# but you can also ask for the minor ticks
In [292]: axis.get_ticklines(minor=True)
Out[292]: 0 Line2D ticklines objects>
刻度格式

刻度格式由 Formatter继承来的类控制。 formatter仅仅作用于单个刻度值并且返回轴的字符串。
相关的子类请参考官方文档。

同样也可以通过重写 __all__ 方法来继承 Formatter 基类以设定自己的formatter。

为了控制主刻度或小刻度标注的格式,使用下面任一方法:

ax.xaxis.set_major_formatter( xmajorFormatter )
ax.xaxis.set_minor_formatter( xminorFormatter )
ax.yaxis.set_major_formatter( ymajorFormatter )
ax.yaxis.set_minor_formatter( yminorFormatter )
### 如何在 Matplotlib设置 X 轴和 Y 轴的刻度 为了控制图表中的轴线外观,可以调整其刻度位置以及标签。当需要自定义这些属性时,`matplotlib` 提供了几种方法来满足需求。 #### 使用 `plt.xticks()` 和 `plt.yticks()` 自定义刻度 对于想要指定特定数值作为刻度的情况,可以直接调用 `plt.xticks()` 或者 `plt.yticks()` 方法,并传递一个包含所需位置列表给它们。例如,在X轴上仅展示偶数索引处的数据点: ```python import numpy as np import matplotlib.pyplot as plt # 创建一些测试数据 x = np.linspace(0, 19, 20) y = x ** 2 fig, ax = plt.subplots() ax.plot(x, y) # 定义新的X轴刻度间隔为2 new_xticks = list(range(0, int(max(x)) + 1, 2)) ax.set_xticks(new_xticks) plt.show() ``` 此段代码设置了X轴上的刻度只会在每两个单位之间出现一次[^1]。 #### 控制主次刻度 有时除了主要的大格子外还需要更细密的小格辅助阅读,则可以通过如下方式开启次要刻度: ```python from matplotlib.ticker import AutoMinorLocator ... # 开启Y轴的自动计算副刻度功能 ax.yaxis.set_minor_locator(AutoMinorLocator()) # 同样也可以应用于X轴 ax.xaxis.set_minor_locator(AutoMinorLocator()) ``` 上述操作将会使得每个大格间均匀分布四个小格[^2]。 #### 设定固定范围内的刻度数量或间距 通过修改 `set_major_formatter()` 可以改变刻度标记的形式;而利用 `MultipleLocator` 类则能轻松地按照固定的步长创建刻度。比如让Y轴始终有五个整数刻度: ```python from matplotlib.ticker import MultipleLocator ... # 设置Y轴每次增加5作为一个新刻度 major_locator = MultipleLocator(base=5.) ax.yaxis.set_major_locator(major_locator) ``` 另外还可以借助于 `MaxNLocator` 实现类似效果——它允许我们指定期望得到的最大刻度数目而不是具体的增量值。 #### 更改默认比例尺 如果不满意当前绘图窗口内两轴的比例关系,那么可通过 `plt.axis('equal')` 告诉程序保持纵横比一致,或者单独使用 `xlim()` / `ylim()` 函数重新规定边界[^3]: ```python ... plt.xlim(-1., max(x)*1.1) # 扩展一点空间以便观察边缘部分 plt.ylim(bottom=-min(y)/10.) # 预留底部空白区域 ``` 以上就是几种常见的用于定制化Matplotlib图像中各条坐标轴样式的技术手段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值