我正在尝试共享两个子图 Axis ,但我需要在创建图形后共享 x Axis 。例如。我创建了这个图:
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 axes
plt.show()
我想插入一些代码来共享两个 x Axis ,而不是注释。
我该怎么做呢?有一些相关的声音属性
_shared_x_axes
和 _shared_x_axes
当我检查图形 Axis ( fig.get_axes()
)但我不知道如何链接它们时。
最佳答案
共享 Axis 的常用方法是在创建时创建共享属性。要么
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
或
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
因此,在创建 Axis 之后共享 Axis 应该是不必要的。
但是,如果出于任何原因,您需要在创建 Axis 后共享 Axis (实际上,使用创建一些子图的不同库,例如 here 可能是一个原因),会有仍然是一个解决方案:
使用
ax1.get_shared_x_axes().join(ax1, ax2)
在 ax1
和 ax2
这两个轴之间创建一个链接。与创建时的共享相比,您必须为其中一个轴手动设置 xticklabels 关闭(以防万一)。
一个完整的例子:
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()
The other answer has code for dealing with a list of axes :
axes[0].get_shared_x_axes().join(axes[0], *axes[1:])
关于python - 创建后如何共享两个子图的 x Axis ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42973223/