1"""
2===================
3Inset Locator Demo2
4===================
5
6This Demo shows how to create a zoomed inset via `~.zoomed_inset_axes`.
7In the first subplot an `~.AnchoredSizeBar` shows the zoom effect.
8In the second subplot a connection to the region of interest is
9created via `~.mark_inset`.
10"""
11
12import matplotlib.pyplot as plt
13
14from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
15from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
16
17import numpy as np
18
19
20def get_demo_image():
21    from matplotlib.cbook import get_sample_data
22    import numpy as np
23    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
24    z = np.load(f)
25    # z is a numpy array of 15x15
26    return z, (-3, 4, -4, 3)
27
28fig, (ax, ax2) = plt.subplots(ncols=2, figsize=[6, 3])
29
30
31# First subplot, showing an inset with a size bar.
32ax.set_aspect(1)
33
34axins = zoomed_inset_axes(ax, zoom=0.5, loc='upper right')
35# fix the number of ticks on the inset axes
36axins.yaxis.get_major_locator().set_params(nbins=7)
37axins.xaxis.get_major_locator().set_params(nbins=7)
38
39plt.setp(axins.get_xticklabels(), visible=False)
40plt.setp(axins.get_yticklabels(), visible=False)
41
42
43def add_sizebar(ax, size):
44    asb = AnchoredSizeBar(ax.transData,
45                          size,
46                          str(size),
47                          loc=8,
48                          pad=0.1, borderpad=0.5, sep=5,
49                          frameon=False)
50    ax.add_artist(asb)
51
52add_sizebar(ax, 0.5)
53add_sizebar(axins, 0.5)
54
55
56# Second subplot, showing an image with an inset zoom
57# and a marked inset
58Z, extent = get_demo_image()
59Z2 = np.zeros([150, 150], dtype="d")
60ny, nx = Z.shape
61Z2[30:30 + ny, 30:30 + nx] = Z
62
63# extent = [-3, 4, -4, 3]
64ax2.imshow(Z2, extent=extent, interpolation="nearest",
65          origin="lower")
66
67
68axins2 = zoomed_inset_axes(ax2, 6, loc=1)  # zoom = 6
69axins2.imshow(Z2, extent=extent, interpolation="nearest",
70              origin="lower")
71
72# sub region of the original image
73x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
74axins2.set_xlim(x1, x2)
75axins2.set_ylim(y1, y2)
76# fix the number of ticks on the inset axes
77axins2.yaxis.get_major_locator().set_params(nbins=7)
78axins2.xaxis.get_major_locator().set_params(nbins=7)
79
80plt.setp(axins2.get_xticklabels(), visible=False)
81plt.setp(axins2.get_yticklabels(), visible=False)
82
83# draw a bbox of the region of the inset axes in the parent axes and
84# connecting lines between the bbox and the inset axes area
85mark_inset(ax2, axins2, loc1=2, loc2=4, fc="none", ec="0.5")
86
87plt.show()
88