แบ่งแกน x ของสองพล็อตย่อยอย่างไรหลังจากสร้างเสร็จแล้ว


97

ฉันกำลังพยายามแบ่งปันแกนย่อยสองแกน แต่ฉันต้องการแบ่งปันแกน 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_axes and _shared_x_axes when i check to figure axis (fig.get_axes()) but I don't know how to link them.

คำตอบ:


137

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 axes might be a reason), there would still be a solution:

Using

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

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

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

The strange reason, by the way, is I saved some figure with pickle and I reload them with another program which looses the sharex property.
ymmx

4
This is useful to connect select subplots. For example, a figure with 4 subplots: two time series and two histograms. This allows you to selectively link the time series.
Hamid

2
API docs for the Grouper object: matplotlib.org/2.0.2/api/…
michaelosthege

3
Ohh, I just figured out how to unshare an axis (which can be useful in a large grid) - on that axis, do g = ax.get_shared_y_axes(); g.remove(a) for a in g.get_siblings(ax)]. Thanks for the starting point!
naught101

3
@naught101 You can just call ax2.autoscale().
ImportanceOfBeingErnest
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.