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, left
, bottom
, width
, height
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 of the total width, from the bottom by of the total height, and the size of the subplot is proportional to 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