简体   繁体   中英

Plotting a horizontal line on multiple subplots in python using pyplot

I am plotting three subplots on the same page. I want to draw a horiZontal line through all the subplots. Following is my code and the resultant graph: (You can notice I can get the horizontal line on one of the plots, but not all)

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()

This generates the following: 在此输入图像描述

Again, I want the line I drew on the last subplot to appear on the first two subplots too. How do I do that?

I found a way to do it for anyone who stumbles on this anyways.

We need to replace the following line from the OP:

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

We replace it with:

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)

This produces:

在此输入图像描述

Since you have defined ax1 , ax2 and ax3 , it is easy to draw horizontal lines on them. You need to do it separately for them. But your code could be simplified:

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

According to axhline documentation , xmin and xmax should be in the range (0,1). There is no chance that xmax=3.0 . Since your intent is to draw horizontal line across the axes (which is the default behavior of axhline method ), you can just omit the xmin and xmax parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM