Matplotlib 实现画中画

需要导入的包 inset_axes

要实现画中画,即在原画轴上添加新轴,需要用到mpl_toolkits.axes_grid1.inset_locatorinset_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()

实际效果

posted @ 2021-11-15 18:03  DGON  阅读(173)  评论(0编辑  收藏  举报