创建两个子图后如何共享它们的 x 轴 [英] How to share x axes of two subplots after they have been created

查看:33
本文介绍了创建两个子图后如何共享它们的 x 轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试共享两个子图轴,但我需要在创建图形后共享 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 might be a reason), there would still be a solution:

使用

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆