慕神8447489
以下是子图的示例图,来自matplotlib:import matplotlib.pyplot as pltimport numpy as np# Some example data to displayx = np.linspace(0, 2 * np.pi, 400)y = np.sin(x ** 2)fig, axs = plt.subplots(2, sharex=True)fig.suptitle('Vertically stacked subplots')axs[0].plot(x, y)axs[1].plot(x, -y)要添加你想要的元素,你可以使用axvlineand text; Text元素可以在图的边界之外(实际上刻度标签是Text)。#continued from above:axs[0].xaxis.set_visible(False)axs[0].axvline(4.5, color='red')axs[0].text(4.5, -.05, 'COG', color='red', transform=axs[0].get_xaxis_transform(), ha='center', va='top')axs[1].axvline(4.5, color='red')axs[1].text(4.5, -.05, 'COG', color='red', transform=axs[1].get_xaxis_transform(), ha='center', va='top')您可以改为添加另一个勾号并更改其颜色:#again, continued from the first code blockaxs[0].xaxis.set_visible(False)axs[0].axvline(4.5, color='red')axs[0].text(4.5, -.05, 'COG', color='red', transform=axs[0].get_xaxis_transform(), ha='center', va='top')ticks = [0, 1, 2, 3, 4, 4.5, 5, 6]labels = [0, 1, 2, 3, 4, "COG", 5, 6]axs[1].axvline(4.5, color='red')axs[1].set_xticks(ticks)axs[1].set_xticklabels(labels)axs[1].get_xticklabels()[5].set_color('red')但是,如果您不想在顶部图表上打勾,那么添加Text(如第一个示例中所示)似乎是最简单的。此外,在第二个示例中手动设置刻度似乎更冗长,并且存在选择要更改的刻度的问题(我在此处进行索引axs[1].get_xticklabels()[5],但对于更多刻度/更复杂的数字,您可能需要更智能的东西)。所以我更喜欢第一种方法而不是这种方法,但它在某些情况下可能会有用(比如如果你想让你的线出现在现有的刻度上)。
catspeake
使用 Toms 的第一个例子可以得到预期的结果。此外,对于标签上重叠文本的情况,我搜索了相邻的刻度标签并将其透明度设置为 != 1。因此,文本“cog”始终可见。import matplotlib.pyplot as pltimport numpy as npxV = 4.5dxV = 1/4 # best 1/4 of the spacing between two ticks# Some example data to displayx = np.linspace(0, 2 * np.pi, 400)y = np.sin(x ** 2)fig, axs = plt.subplots(2, sharex=True)fig.suptitle('Vertically stacked subplots')axs[0].plot(x, y)axs[0].xaxis.set_visible(False)axs[0].axvline(xV, color='red')axs[0].text(xV, -.05, 'COG', color='red', transform=axs[0].get_xaxis_transform(), ha='center', va='top')axs[1].plot(x, -y)axs[1].axvline(xV, color='red')axs[1].text(xV, -.05, 'COG', color='red', transform=axs[1].get_xaxis_transform(), ha='center', va='top')# Change Transparency if too closexticks = axs[1].xaxis.get_major_ticks()values = axs[1].get_xticks()# values = axs[1].xaxis.get_major_locator()()pos = np.where(np.logical_and( (xV-dxV) <= values, (xV+dxV) >= values))[0]if pos.size > 0: dist = np.abs(values[pos]-xV) pos = pos[dist.argmin()] xticks[pos].label1.set_alpha(0.5)plt.show()