29

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: enter image description here

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

Abhinav Kumar
  • 1,613
  • 5
  • 20
  • 33
  • 1
    In general, the less un-needed details (like your axes labels, your actual data) your question contains the better. It is best if your code is copy-paste-runable. – tacaswell Jan 15 '14 at 15:11

2 Answers2

47

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:

enter image description here

Abhinav Kumar
  • 1,613
  • 5
  • 20
  • 33
  • 2
    Please remember to accept your own answer when it will let you. You might also want to read https://stackoverflow.com/questions/16849483/which-is-the-recommended-way-to-plot-matplotlib-or-pylab/16849816#16849816 for an explanation of the pyplot vs OO interface. – tacaswell Jan 15 '14 at 15:07
  • According to [documentation](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.axhline.html#matplotlib.pyplot.axhline), both `xmin` and `xmax` should be in the range [0,1]. using `xmax=3` is misleading here. – jdhao May 22 '18 at 03:17
5

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.

jdhao
  • 24,001
  • 18
  • 134
  • 273