Matplotlib 實現畫中畫
需要導入的包 inset_axes
要實現畫中畫,即在原畫軸上添加新軸,需要用到mpl_toolkits.axes_grid1.inset_locator的inset_axes.
基本用法
new_axis=inset_axes(parent_axes, width, height, loc='upper right',borderpad=0.5)
參數說明
parent_axes:父軸,即背景軸;
width:新軸寬度
height:新軸高度
loc:新軸在父軸上位置,包括:
| str | code |
|---|---|
| 'upper right' | 1 |
| 'upper left' | 2 |
| 'lower left' | 3 |
| 'lower right' | 4 |
| 'right' | 5 |
| 'center left' | 6 |
| 'center right' | 7 |
| 'lower center' | 8 |
| 'upper center' | 9 |
| 'center' : | 10 |
======================================
可以寫做loc='upper right'或者loc=1。
borderpad:新軸與父軸間距。
完整代碼
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
plt.rcParams['font.family'] = 'Noto Sans CJK JP'
plt.rcParams['axes.unicode_minus'] = False
def fun_power(x):
c = np.exp(-(x ** 2))
return c
def picture_in_picture():
x0 = np.linspace(0, 20, 200)
x2 = np.linspace(0, 2 * np.pi, 200)
y1 = np.cos(x0)
y4 = fun_power(x2)
fig, axes = plt.subplots(figsize=(40, 20))
ax1 = plt.subplot()
num = np.arange(0, 0.5, 0.1) * np.pi
for i in num:
y = y1 * fun_power(i)
symbol = (i / np.pi)
ax1.plot(x0, y, label='y={}'.format(symbol.round(1)) + r'$\times\pi$')
plt.legend()
plt.title('多元函數'+r'$:z=\sin{x}\times e^{-y^2}$')
plt.ylim(-2,1.5)
plt.grid()
new_ax = inset_axes(ax1, width="40%", height="20%", loc='lower right', borderpad=5)
new_ax.plot(x2, y4)
num = ['{}'.format(i / 2) for i in range(0,5,1)]
x_labels = [i + r'$\pi$' for i in num]
plt.xticks(np.arange(0, 2 * np.pi + 0.01, np.pi / 2), labels=x_labels)
plt.yticks(np.arange(0, 1.1, 0.2))
plt.title('放大因子'+r'$:e^{-y^2}$')
plt.grid()
plt.savefig('potential.pdf')
plt.show()
if __name__ == '__main__':
picture_in_picture()

浙公網安備 33010602011771號