matplotlib 如何在创建两个子地块后共享它们的x轴

mspsb9vt  于 2023-05-18  发布在  其他
关注(0)|答案(4)|浏览(111)

我试图共享两个子图轴,但在创建图形后,我需要共享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 axes

plt.show()

我想插入一些代码来共享两个x轴,而不是注解。我该怎么做?当我检查到图形轴(fig.get_axes())时,有一些相关的声音属性_shared_x_axes_shared_x_axes,但我不知道如何链接它们。

lfapxunr

lfapxunr1#

共享轴的通常方法是在创建时创建共享特性。要么

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

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)

因此,在创建轴之后共享轴应该是不必要的。
但是,如果出于任何原因,您需要在创建轴后共享轴(实际上,使用不同的库创建一些子图,如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:])
owfi6suc

owfi6suc2#

从Matplotlib v3.3开始,现在存在Axes.sharexAxes.sharey方法:

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

yzuktlbb3#

下面是ImportanceOfBeingErnest的回答:
如果你有一个完整的list轴对象,你可以一次传递所有的轴,并通过如下解压缩列表来共享它们的轴:

ax_list = [ax1, ax2, ... axn] #< your axes objects 
ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list)

上面的内容将把所有这些联系在一起。当然,你可以发挥创造性,将list子集设置为仅链接其中的一部分。

注:

为了将所有的axes链接在一起,您必须在调用中包含axes_list的第一个元素,尽管您是在第一个元素上调用.get_shared_x_axes()
所以这样做,这显然是合乎逻辑的:

ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list[1:])

...将导致所有axes对象链接在一起除了第一个对象,它将保持完全独立于其他对象。

p5cysglq

p5cysglq4#

函数join已被弃用,将很快删除。不建议继续使用此功能。
你可以使用iacob建议的方法,但正如特雷弗Boyd Smith所评论的,sharexsharey只能在同一个对象上调用一次。
因此,解决方案是选择一个单个轴作为来自多个轴的调用的自变量,这些轴需要与第一个轴相关联,例如要为轴ax1ax2ax3设置相同的y刻度:

  • 选择ax1作为其他调用的参数。
  • 如果需要,调用ax2.sharey(ax1)ax3.sharey(ax1)等等。

相关问题