Drawing Subplots at Desired Arbitrary Locations or Overlapping in Python matplotlib
Overview
Using plt.subplot
or gridspec
, you can create subplots in simple or complex grid-based layouts. This article introduces a method to draw subplots at completely arbitrary positions, independent of the grid system.
Code
fig.add_axes([left, bottom, width, height])
By using add_axes
, you can create a new subplot at a desired location on the figure. The area of the subplot is determined by the input arguments [left, bottom, width, height]
. Each item represents a ratio of the total figure, thus, $0 \le$ left
, bottom
, width
, height
$\le 1$ must be satisfied. For example, fig.add_axes([0.1, 0.1, 0.2, 0.3])
creates a subplot that is detached from the left by $1/10$ of the total width, from the bottom by $1/10$ of the total height, and the size of the subplot is proportional to $0.2 \times 0.3$ of the total figure size. The reference point for the position is the bottom-left corner of the subplot.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.2, 0.3])
ax1.plot(np.random.randn(10))
plt.show()
Because you can draw at absolutely any location, it is also possible to overlap subplots. The first drawn subplot will lie underneath.
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.8])
ax1.plot(np.random.randn(10))
ax2 = fig.add_axes([0.4, 0.5, 0.4, 0.4])
plt.bar(np.arange(10), np.random.randn(10))
ax3 = fig.add_axes([0.7, 0.4, 0.2, 0.2])
ax3.scatter(np.random.randn(10), np.random.randn(10))
plt.show()
Environment
- OS: Windows11
- Version: Python 3.9.13, matplotlib==3.6.2, numpy==1.23.5