python - 创建后如何共享两个子图的 x Axis

标签 python matplotlib axis

我正在尝试共享两个子图 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)

ax1ax2 这两个轴之间创建一个链接。与创建时的共享相比,您必须为其中一个轴手动设置 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/

相关文章:

c# - 将两个 y Axis 分配给 oxyplot 中的两个线系列(C# WPF)

python - 每两列相加

python - Markevery 的 FuncAnimation 难度

python - 计算不包含某些字符串 Pandas DataFrames 的行

python - matplotlib 程序运行时窗口无响应

Matplotlib 在 imshow 上绘图,同时保持 Axis 大小

python - 如何将光标对象的输出存储到文本文件?

python - 在一个图中叠加两个密度

python - 如何使用 matplotlib 在 cartopy 极地立体图中获得平滑的网格线?

python - 如何消除matplotlib Axis 的相对偏移