如何在 Python Matplotlib 中添加第三级刻度?
要在 Python Matplotlib 中添加第三级刻度,我们可以采取以下步骤:
- 设置图形大小并调整子图之间和周围的填充。
- 使用 numpy 创建 t 和 s 数据点。
- 创建一个图形和一组子图。
- 使用 plot() 方法绘制 t 和 s。
- 创建共享 Y 轴的双轴。
- 使用 plot() 方法在第一个轴上绘制 t 和 s。
- 设置 X 轴刻度位置。
- 创建主刻度值 majors、次刻度值 minors 和第三级刻度值 (thirds)。
- 使用 majors、minors 和第三级刻度值 (thirds) 设置主刻度和次刻度定位器。
- 使用 tick_params() 设置刻度长度。
- 绘制一条灰色水平线。
- 要显示图形,请使用 show() 方法。
示例
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)
fig, ax = plt.subplots()
plt.plot(t, s)
ax1 = ax.twiny()
ax1.plot(t, s)
ax1.xaxis.set_ticks_position('bottom')
majors = np.linspace(0, 100, 6)
minors = np.linspace(0, 100, 11)
thirds = np.linspace(0, 100, 101)
ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator(majors))
ax.xaxis.set_minor_locator(matplotlib.ticker.FixedLocator(minors))
ax1.xaxis.set_major_locator(matplotlib.ticker.FixedLocator([]))
ax1.xaxis.set_minor_locator(matplotlib.ticker.FixedLocator(thirds))
ax1.tick_params(which='minor', length=2)
ax.tick_params(which='minor', length=4)
ax.tick_params(which='major', length=6)
ax.grid(which='both', axis='x', linestyle='--')
plt.axhline(color='gray')
plt.show()输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP