在pyplot中标注x轴下方的垂直线

3

我正在使用matplotlib,试图在连续数据的图形上注释我画出的垂直线。使用以下代码:

plt.annotate('%.2f' % 2.34, xy=(0,0), xytext=(0,-20), xycoords='axes fraction', textcoords='offset points',color='r')

我能够让文本显示在我的图形下方。然而,我已经绘制了垂直线 - 比如说每隔240个单位 - 我想要在x轴下方具体注释每一条线。
我尝试将xycoords格式切换为"data",然后使用xy=(240,0),但是当我将xycoords格式切换为"data"时,注释文本不再出现在我的图形中。
我还尝试计算我想要放置注释的位置的分数(例如240/图形长度),但这仍然没有正确地放置它。
为什么当我将坐标系从“axis fraction”更改为“data”时,注释命令停止向我的图形添加文本?谢谢!
1个回答

3

没有可行的例子,很难确定问题的确切原因。无论如何,我建议您解决问题的方法是复制您的轴(在同一图中),并仅使用第二个轴来控制附属物。

以下是一个可行的解决方案:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

# Add some extra space for the second axis at the bottom
fig.subplots_adjust(bottom=0.2)
ax1.set_xticks(range(-100, 100, 10))
ax1.set_xlim(-100, 100)
ax1.set_xticklabels([str(i) for i in range(-100, 100, 10)], rotation=45)

ax2.spines["bottom"].set_position(("axes", -0.1))
ax2.xaxis.set_ticks_position("bottom")
ax2.spines["bottom"].set_visible(True)
ax2.set_xticks([-50,50])
ax2.set_xticklabels(['Line 1', 'Line 2'], rotation=45, color='blue')
ax2.set_xlim(-100, 100)

b1 = np.random.randint(0,100,6)
b2 = np.random.randint(0,100,6)
b3 = np.random.randint(0,100,6)
ax1.scatter(np.random.normal(0, 1, 100)*100, np.random.normal(0, 1, 100)*100, c='green', s=90)
ax1.axvline(-50)
ax1.axvline(50)

plt.show()

这会导致如下的结果:

在一个图中使用第二个轴为matplotlib中的vlines提供标签


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接