Python 创建后如何共享两个子图的 x 轴?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42973223/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:19:21  来源:igfitidea点击:

How share x axis of two subplots after they are created?

pythonmatplotlibshareaxis

提问by ymmx

I'm trying to share two subplots axis, but I need to share x axis after the figure was created. So, for instance, I create this figure:

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

Instead of the comment I would insert some code to share both x axis. I didn't find any clue how i can do that. There are some attributes _shared_x_axesand _shared_x_axeswhen i check to figure axis (fig.get_axes()) but I don't know how to link them.

我会插入一些代码来共享两个 x 轴,而不是注释。我没有找到任何线索如何做到这一点。有一些属性 _shared_x_axes_shared_x_axes当我检查图形轴 ( fig.get_axes()) 时,但我不知道如何链接它们。

回答by ImportanceOfBeingErnest

The usual way to share axes is to create the shared properties at creation. Either

共享轴的常用方法是在创建时创建共享属性。任何一个

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

or

或者

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

Sharing the axes after they have been created should therefore not be necessary.

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

However if for any reason, you need to share axes after they have been created(actually, using a different library which creates some subplots, like here, or sharing an inset axesmight be a reason), there would still be a solution:

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

Using

使用

ax1.get_shared_x_axes().join(ax1, ax2)

creates a link between the two axes, ax1and ax2. In contrast to the sharing at creation time, you will have to set the xticklabels off manually for one of the axes (in case that is wanted).

在两个轴之间创建链接,ax1并且ax2。与创建时的共享相反,您必须为轴之一手动设置 xticklabels(以防万一)。

A complete example:

一个完整的例子:

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()