Python 创建两个子地块后,如何共享它们的x轴?

Python 创建两个子地块后,如何共享它们的x轴?,python,matplotlib,share,axis,Python,Matplotlib,Share,Axis,我试图共享两个子地块轴,但我需要在图形创建后共享x轴。 例如,我创建了一个图: import numpy as np import matplotlib.pyplot as plt t= np.arange(1000)/100. x = np.sin(2*np.pi*10*t) y = np.cos(2*np.pi*10*t) fig=plt.figure() ax1 = plt.subplot(211) plt.plot(t,x) ax2 = plt.subplot(212) plt.pl

我试图共享两个子地块轴,但我需要在图形创建后共享x轴。 例如,我创建了一个图:

import numpy as np
import matplotlib.pyplot as plt

t= np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)

fig=plt.figure()
ax1 = plt.subplot(211)
plt.plot(t,x)
ax2 = plt.subplot(212)
plt.plot(t,y)

# some code to share both x axis

plt.show()
我将插入一些代码来共享x轴,而不是注释。 我找不到任何线索,我怎么能做到这一点。有一些属性
\u shared_x_axes
\u shared_x_axes
当我检查图形轴(
图get_axes()
)时,但我不知道如何链接它们。

共享轴的常用方法是在创建时创建共享属性。或者

fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)

因此,无需在创建轴后共享轴

但是,如果出于任何原因,您需要在创建轴后共享轴(实际上,使用不同的库创建一些子图,这可能是一个原因),仍然有一个解决方案:

使用

在两个轴之间创建链接,
ax1
ax2
。与创建时的共享不同,您必须为其中一个轴手动设置Xticklabel(如果需要)

一个完整的例子:

import numpy as np
import matplotlib.pyplot as plt

t= np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)

fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)

ax1.plot(t,x)
ax2.plot(t,y)

ax1.get_shared_x_axes().join(ax1, ax2)
ax1.set_xticklabels([])
# ax2.autoscale() ## call autoscale if needed

plt.show()

只是为了补充上述Beingernest答案的重要性:

如果您有一个完整的轴对象
列表
,您可以一次将它们全部传递,并通过如下方式解包列表,共享它们的轴:

ax_list = [ax1, ax2, ... axn] #< your axes objects 
ax_list[0].get_shared_x_axes().join(*ax_list)
。。。将导致将所有
对象链接在一起,但第一个对象除外,它将保持与其他对象完全独立。

自Matplotlib起,现在存在
轴。sharex
轴。sharey
方法:

ax1.sharex(ax2)
ax1.sharey(ax3)

顺便说一句,奇怪的原因是我用pickle保存了一些图形,然后用另一个程序重新加载它们,该程序释放了sharex属性。这对于连接选择的子地块很有用。例如,一个具有4个子图的图形:两个时间序列和两个直方图。这允许您有选择地链接Grouper对象的time series.API文档:哦,我刚刚想出了如何取消共享轴(在大型网格中可能很有用)-在该轴上,执行
g=ax.get_shared_y_axes();g、 删除g中a的(a)。获取(ax)]
。谢谢你的出发点@您只需调用
ax2.autoscale()
ax_list = [ax1, ax2, ... axn] #< your axes objects 
ax_list[0].get_shared_x_axes().join(*ax_list)
ax_list[0].get_shared_x_axes().join(*ax_list[1:])
ax1.sharex(ax2)
ax1.sharey(ax3)