使用pyplot在python中的多个子图上绘制水平线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21129007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plotting a horizontal line on multiple subplots in python using pyplot
提问by Abhinav Kumar
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?
同样,我希望我在最后一个子图上绘制的线也出现在前两个子图上。我怎么做?
采纳答案by Abhinav Kumar
I found a way to do it for anyone who stumbles on this anyways.
我找到了一种方法来为任何偶然发现这个问题的人做这件事。
We need to replace the following line from the OP:
我们需要替换 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:
这产生:


回答by jdhao
Since you have defined ax1, ax2and ax3, it is easy to draw horizontal lines on them. You need to do it separately for them. But your code could be simplified:
由于您已定义ax1,ax2和ax3,因此很容易在它们上绘制水平线。你需要为他们单独做。但是您的代码可以简化:
for ax in [ax1, ax2, ax3]:
ax.axhline(y=0.002, c="blue",linewidth=0.5,zorder=0)
According to axhline documentation, xminand xmaxshould 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 axhlinemethod ), you can just omit the xminand xmaxparameter.
据axhline文档,xmin并xmax应该是在范围(0,1)。没有机会xmax=3.0。由于您的意图是在轴上绘制水平线(这是axhlinemethod的默认行为),您可以省略xminandxmax参数。

