Different X and Y scales in zoomed inset in Matplotlib

MatplotlibPythonData Visualization

To show different X and Y scales in zoomed inset in Matplotlib, we can use inset_axes() method.

Steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Create x and y data points using numpy.
  • Add a subplot to the current figure.
  • Plot x and y data points using plot() method.
  • Create an inset axes with a given width and height.
  • Set different x and y scales.
  • Draw a box to mark the location of an area represented by an inset axes.
  • To display the figure, use show() method.

Example

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import mark_inset, inset_axes

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(0, 1, 100)
y = x ** 2

ax = plt.subplot(1, 1, 1)
ax.plot(x, y)

axins = inset_axes(ax, 1, 1, loc=2, bbox_to_anchor=(0.2, 0.55),
                  bbox_transform=ax.figure.transFigure)
axins.plot(x, y)

x1, x2 = .4, .6
y1, y2 = x1 ** 2, x2 ** 2

axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)

mark_inset(ax, axins, loc1=1, loc2=3, fc="none", ec="0.5")

plt.show()

Output

raja
Published on 17-Jun-2021 11:56:31
Advertisements