[Python] Matplotlib partial enlargement drawing method

[Python] Matplotlib partial enlargement drawing method

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib.patches import ConnectionPatch

x = np.arange(1,len(LSTM_true)+1)

# 画出测试集的实际结果和预测结果
fig, ax = plt.subplots(figsize=(30, 12))
ax.plot(x, LSTM_true,color='black', label='true', alpha=0.7)
ax.plot(x, LSTM_predict,color='#848484', label='LSTM', alpha=0.7)
ax.plot(x, MLP_predict, color='#FF774A',label='MLP', alpha=0.7)
ax.plot(x, RNN_predict,  color='#575B20',label='RNN', alpha=0.7)
ax.plot(x, TCN_predict,label='TCN', alpha=0.7)
ax.plot(x, XGBoost_predict,label='XGBoost', alpha=0.7)
ax.plot(x, CNN_predict,label='CNN', alpha=0.7)
ax.plot(x, Transformer_predict,label='Transformer', alpha=0.7)

plt.legend(loc='best')

# 嵌入局部放大图的坐标系 
#ax为父坐标系,后面四个参数同样是(x0, y0, width, height),
axins = ax.inset_axes((0.2, -0.5, 0.4, 0.3))

#在子坐标系中绘制原始数据
axins.plot(x, LSTM_true,color='black', label='true', alpha=0.7)
axins.plot(x, LSTM_predict,color='#848484', label='LSTM', alpha=0.7)
axins.plot(x, MLP_predict, color='#FF774A',label='MLP', alpha=0.7)
axins.plot(x, RNN_predict,  color='#575B20',label='RNN', alpha=0.7)
axins.plot(x, TCN_predict,label='TCN', alpha=0.7)
axins.plot(x, XGBoost_predict,label='XGBoost', alpha=0.7)
axins.plot(x, CNN_predict,label='CNN', alpha=0.7)
axins.plot(x, Transformer_predict,label='Transformer', alpha=0.7)

# 设置放大区间,调整子坐标系的显示范围
# 设置放大区间
zone_left = 100
zone_right = 130

# 坐标轴的扩展比例(根据实际数据调整)
x_ratio = 0  # x轴显示范围的扩展比例
y_ratio = 0.05  # y轴显示范围的扩展比例

# X轴的显示范围
xlim0 = x[zone_left]-(x[zone_right]-x[zone_left])*x_ratio
xlim1 = x[zone_right]+(x[zone_right]-x[zone_left])*x_ratio

# Y轴的显示范围
y = np.hstack((LSTM_true[zone_left:zone_right], LSTM_predict[zone_left:zone_right],
               MLP_predict[zone_left:zone_right],RNN_predict[zone_left:zone_right]))
ylim0 = np.min(y)-(np.max(y)-np.min(y))*y_ratio
ylim1 = np.max(y)+(np.max(y)-np.min(y))*y_ratio

# 调整子坐标系的显示范围
axins.set_xlim(xlim0, xlim1)
axins.set_ylim(ylim0, ylim1)

# 建立父坐标系与子坐标系的连接线
# 原图中画方框
tx0 = xlim0
tx1 = xlim1
ty0 = ylim0
ty1 = ylim1
sx = [tx0,tx1,tx1,tx0,tx0]
sy = [ty0,ty0,ty1,ty1,ty0]
ax.plot(sx,sy,"black")

# 画两条线
xy = (xlim0,ylim0)
xy2 = (xlim0,ylim1)
con = ConnectionPatch(xyA=xy2,xyB=xy,coordsA="data",coordsB="data",
        axesA=axins,axesB=ax)
axins.add_artist(con)

xy = (xlim1,ylim0)
xy2 = (xlim1,ylim1)
con = ConnectionPatch(xyA=xy2,xyB=xy,coordsA="data",coordsB="data",
        axesA=axins,axesB=ax)
axins.add_artist(con)

plt.savefig(r'C:\Users\ZHUANG\Desktop\pjm_rto_load.png')


Insert image description here
For details, see https://juejin.cn/post/6844904183548608520

Guess you like

Origin blog.csdn.net/weixin_66397563/article/details/131799817