创建两个子图后如何共享它们的x轴? [英] How share x axis of two subplots after they are created?
问题描述
我试图共享两个子图轴,但是在创建图形之后,我需要共享x轴. 因此,例如,我创建了这个图:
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:
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轴,而不是注释.
我没有找到任何线索我可以做到这一点.有一些属性
_shared_x_axes
和_shared_x_axes
当我检查图轴(fig.get_axes()
)但不知道如何链接它们时.
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_axes
and _shared_x_axes
when i check to figure axis (fig.get_axes()
) but I don't know how to link them.
推荐答案
共享轴的常用方法是在创建时创建共享属性.要么
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)
或
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 axes might be a reason), there would still be a solution:
使用
ax1.get_shared_x_axes().join(ax1, ax2)
在两个轴ax1
和ax2
之间创建链接.与创建时的共享相比,您必须为其中一个轴手动设置xticklabel(以防万一).
creates a link between the two axes, ax1
and 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).
完整示例:
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()
这篇关于创建两个子图后如何共享它们的x轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!