ymm*_*mmx 66 python axis share matplotlib
我正在尝试共享两个子图轴,但我需要在创建图形后共享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()
Run Code Online (Sandbox Code Playgroud)
而不是评论我会插入一些代码来共享两个x轴.我没有找到任何线索我怎么能这样做.有一些属性
_shared_x_axes
,_shared_x_axes
当我检查图轴(fig.get_axes()
)但我不知道如何链接它们.
Imp*_*est 88
共享轴的常用方法是在创建时创建共享属性.或
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
Run Code Online (Sandbox Code Playgroud)
要么
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
Run Code Online (Sandbox Code Playgroud)
因此,在创建轴之后共享轴不是必需的.
但是,如果由于任何原因,您需要在创建轴之后共享轴(实际上,使用创建一些子图的不同库,如此处,或共享插入轴可能是一个原因),仍然会有一个解决方案:
运用
ax1.get_shared_x_axes().join(ax1, ax2)
Run Code Online (Sandbox Code Playgroud)
创建两个轴之间的链接,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()
Run Code Online (Sandbox Code Playgroud)
uke*_*emi 10
由于Matplotlib的V3.3现在存在着Axes.sharex
,Axes.sharey
方法:
ax1.sharex(ax2)
ax1.sharey(ax3)
Run Code Online (Sandbox Code Playgroud)
只是补充一下 ImportanceOfBeingErnest 上面的答案:
如果您有一整套list
轴对象,您可以一次传递它们,并通过解压列表来共享它们的轴,如下所示:
ax_list = [ax1, ax2, ... axn] #< your axes objects
ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list)
Run Code Online (Sandbox Code Playgroud)
上面将把它们全部链接在一起。当然,您可以发挥创意并细分您的list
以仅链接其中的某些内容。
笔记:
为了将所有内容axes
链接在一起,您必须axes_list
在调用中包含第一个元素,尽管您是.get_shared_x_axes()
从第一个元素开始调用的!
所以这样做,这肯定是合乎逻辑的:
ax_list[0].get_shared_x_axes().join(ax_list[0], *ax_list[1:])
Run Code Online (Sandbox Code Playgroud)
...将导致除axes
第一个对象之外的所有对象链接在一起,第一个对象将完全独立于其他对象。