简体   繁体   中英

How to make matplotlib.pyplot subplots that overlap?

I am learning how to use subplots. For example:

import numpy
import matplotlib.pyplot as plt

plt.figure(1)
plt.subplot(221)
plt.subplot(222)
plt.subplot(223)

plt.show()

plt.close(1)

I am getting 3 subplots in figure1

Now I want to make a large subplot with the other subplots within the first one. I tried:

plt.figure(1)
plt.subplot(111)
plt.subplot(222)
plt.subplot(223)

But the first subplot disappears.

My question: is it possible to overlap subplots?

thank you

If you want a total control of the subplots size and position, use Matplotlib add_axes method instead.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 4))

ax1 = fig.add_axes([0.1, 0.1, 0.85, 0.85])
ax2 = fig.add_axes([0.4, 0.6, 0.45, 0.3])
ax3 = fig.add_axes([0.6, 0.2, 0.2, 0.65])

ax1.text(0.01, 0.95, "ax1", size=12)
ax2.text(0.05, 0.8, "ax2", size=12)
ax3.text(0.05, 0.9, "ax3", size=12)

plt.show()

伊格

It's not possible to use plt.subplots() to create overlapping subplots. Also, plt.subplot2grid will not work.

However, you can create them using the figure.add_subplot() method.

import matplotlib.pyplot as plt
fig = plt.figure(1)
fig.add_subplot(111)
fig.add_subplot(222)
fig.add_subplot(223)

plt.show()

在此处输入图片说明

You can use mpl_toolkits.axes_grid1.inset_locator.inset_axes to create an inset axes on an existing figure. I added a print statement at the end which shows a list of two axes.

import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator as mpl_il

plt.plot() 

ax2 = mpl_il.inset_axes(plt.gca(), width='60%', height='40%', loc=6)
ax2.plot()

print(plt.gcf().get_axes())
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