使用pyp在python中绘制多个子块上的水平线

2024-06-06 22:08:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在同一页上画了三个小段。我想在所有的子区画一条水平线。下面是我的代码和生成的图表:(您可以注意到,我可以在其中一个图上获得水平线,但不是全部)

gs1 = gridspec.GridSpec(8, 2)
gs1.update(left=0.12, right=.94, wspace=0.12)
ax1 = plt.subplot(gs1[0:2, :])
ax2 = plt.subplot(gs1[3:5, :], sharey=ax1)
ax3 = plt.subplot(gs1[6:8, :], sharey=ax1)

ax1.scatter(theta_cord, density, c = 'r', marker= '1')
ax2.scatter(phi_cord, density, c = 'r', marker= '1')
ax3.scatter(r_cord, density, c = 'r', marker= '1')
ax1.set_xlabel('Theta (radians)')
ax1.set_ylabel('Galaxy count')
ax2.set_xlabel('Phi (radians)')
ax2.set_ylabel('Galaxy count')
ax3.set_xlabel('Distance (Mpc)')
ax3.set_ylabel('Galaxy count')
plt.ylim((0,0.004))
loc = plticker.MultipleLocator(base=0.001)
ax1.yaxis.set_major_locator(loc)

plt.axhline(y=0.002, xmin=0, xmax=1, hold=None)

plt.show()

这将产生以下结果: enter image description here

同样,我希望我在最后一个子块上画的线也出现在前两个子块上。我该怎么做?


Tags: countpltdensitygalaxygs1markersetscatter
2条回答

因为您已经定义了ax1ax2ax3,所以很容易在它们上绘制水平线。你得为他们单独做。但你的代码可以简化:

for ax in [ax1, ax2, ax3]:
    ax.axhline(y=0.002, c="blue",linewidth=0.5,zorder=0)

根据axhline documentationxminxmax应该在(0,1)范围内。不可能xmax=3.0。因为您的目的是在轴上画水平线(这是axhline方法的默认行为),所以您可以省略xminxmax参数。

我找到了一个方法,为任何人谁绊倒了这无论如何。

我们需要替换OP的以下行:

plt.axhline(y=0.002, xmin=0, xmax=1, hold=None)

我们将其替换为:

ax1.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0.5,zorder=0)
ax2.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0.5,zorder=0)
ax3.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0.5,zorder=0)

这会产生:

enter image description here

相关问题 更多 >