简体   繁体   中英

Matplotlib: Sharing axes when having 3 graphs 2 at the left and 1 at the right

I have following graph: 在此处输入图片说明

However, I want that graphs 221 and 223 share the same x axis. I have the following code:

self.fig_part_1 = plt.figure()
self.plots_part_1 = [
  plt.subplot(221),
  plt.subplot(223),
  plt.subplot(122),
]

How can I achieve that? In the end I do not want the numbers of axis x in plot 221 to be shown.

Just use plt.subplots (different from plt.subplot ) to define all your axes, with the option sharex=True :

f, axes = plt.subplots(2,2, sharex=True)
plt.subplot(122)
plt.show()

Note that the second call with larger subplot array overlay the preceding one.

Example (could not display image due to reputation...)

(This is mostly a comment to @H. Rev. but I post it as an "answer" to get nicer code formatting)

I think it is way better to just add the subplots manually, since as you implemented it now it will give two axes that you just throw away. They might even give problems with overlapping axis-ticks and a lot of confusion in general. I believe it is better to create the figure first, and then add axes one by one. This way also solves the problem by having to "update" the current figure with plt.figure(self.f.number) since you have direct access to eg fig_N

import matplotlib.pyplot as plt

fig1 = plt.figure()
# fig2 = plt.figure()  # more figures are easily accessible
# fig3 = plt.figure()  # more figures are easily accessible

ax11 = fig1.add_subplot(221)  # add subplot into first position in a 2x2 grid (upper left)
ax12 = fig1.add_subplot(223, sharex=ax11)  # add to third position in 2x2 grid (lower left) and sharex with ax11
ax13 = fig1.add_subplot(122)  # add subplot to cover both upper and lower right, in a 2x2 grid. This is the same as the rightmost panel in a 1x2 grid.
# ax21 = fig2.add_subplot(211)  # add axes to the extra figures
# ax21 = fig2.add_subplot(212)  # add axes to the extra figures
# ax31 = fig3.add_subplot(111)  # add axes to the extra figures
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM