1

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

2
  • You've accepted an answer that doesn't answer the question, while there is another answer that DOES. Commented Jul 17, 2021 at 7:36
  • Sorry P i , not sure if I understand your complaint. All answers were good, and I vote them all up. However, the one I accepted is the one that solved my question. Commented Aug 13, 2021 at 17:45

3 Answers 3

8

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

Imgur

Sign up to request clarification or add additional context in comments.

Comments

3

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

Creating inset axes on existing figure

Comments

2

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

enter image description here

2 Comments

Both methods are very interesting (add_subplot and add_axes). But add_subplot is exactly the answer I was looking for. Is there any advantage using one or the other?
They are very different. add_subplot creates an axes according to some grid. The advantange is that the grid may later be modified and the axes sticks to it, e.g. one can call plt.tight_layout() or plt.subplots_adjust. In contrast add_axes puts the axes at the position specfied. It will then stay where it is. This can be an advantage or a disadvantage depending on the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.