需求

使用 matplot 时,需要使用顶部的 X 轴,并且添加两个 X 轴的辅助线

解决

双X轴可以使用 twiny, 辅助线可以使用 MultipleLocator

!/usr/bin/python3

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


sin_num = 2

x = np.linspace(0, 50, 150)

y_ok = np.sin(x / sin_num) * 3 + 6
y1 = y_ok[ : 120]
y2 = y_ok[ : 120]
x_1 = x[ : 120]
#x2 = np.linspace(0, 30, 120)

fig, axes = plt.subplots()
fig.set_size_inches(10, 5)
axes.set_xlabel('before')
axes.set_ylabel('glucose')
axes.plot(x_1, y1, color = 'green', label = 'before')
axes.plot(x_1 / 0.8, y2, color = 'red', label = 'after')
axes.set_xticks([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50], ['0:00', '1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00'], color='green')
axes.legend()
xmajorLocator = MultipleLocator(5)
#xmajorFormatter = FormatStrFormatter
axes.xaxis.set_major_locator(xmajorLocator)
axes.xaxis.grid(True, which='major', linestyle="dashed", color="darkgreen", linewidth=0.75)


x1, x2 = axes.get_xlim()
twin_axes = axes.twiny()
twin_axes.set_xlabel('after')
twin_axes.set_xlim(x1, x2)
twin_axes.set_xticks([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50], ['0:00', '1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00'], color='red')
twin_xml = MultipleLocator(5)
twin_axes.xaxis.set_major_locator(twin_xml)
twin_axes.xaxis.grid(True, which='major', linestyle="dotted", color="darkred", linewidth=0.75)

fig.suptitle("C2")
plt.show()

参考