Python中的 Matplotlib.ticker.MaxNLocator 类
Matplotlib是Python中用于数组二维图的惊人可视化库。 Matplotlib 是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈配合使用。
matplotlib.ticker.MaxNLocator
matplotlib.ticker.MaxNLocator
类用于在不错的位置选择不超过 N 个间隔。它是matplotlib.ticker.Locator
的子类。
Syntax: class matplotlib.ticker.MaxNLocator(*args, **kwargs)
Parameter:
- nbins: It is either an integer or ‘auto’, where the integer value represents the maximum number of intervals; one less than max number of ticks. The number of bins gets automatically determined on the basis of the length of the axis.It is an optional argument and has a default value of 10.
- steps: It is an optional parameter representing a nice number sequence that starts from 1 and ends with 10.
- integer: It is an optional boolean value. If set True, the ticks accepts only integer values, provided at least min_n_ticks integers are within the view limits.
- symmetric: It is an optional value. If set to True, auto-scaling will result in a range symmetric about zero.
- prune: It is an optional parameter that accepts either of the four values: {‘lower’, ‘upper’, ‘both’, None}. By default it is None.
类的方法:
- set_params(self, **kwargs):它为定位器设置参数。
- tick_values(self, vmin, vmax):它返回给定 vmin 和 vmax 的已定位刻度的值。
- view_limits(self, dmin, dmax):用于选择从 vmin 到 vmax 的范围。
示例 1:
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np
N = 10
x = np.arange(N)
y = np.random.randn(N)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
# Create your ticker object with M ticks
M = 3
yticks = ticker.MaxNLocator(M)
# Set the yaxis major locator using
# your ticker object.
ax.yaxis.set_major_locator(yticks)
plt.show()
输出:
示例 2:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator, IndexFormatter
ax = df.plot()
ax.xaxis.set_major_locator(MaxNLocator(11))
ax.xaxis.set_major_formatter(IndexFormatter(df.index))
ax.grid(which ='minor', alpha = 0.2)
ax.grid(which ='major', alpha = 0.5)
ax.legend().set_visible(False)
plt.xticks(rotation = 75)
plt.tight_layout()
plt.show()
输出: