图像看不清,打算再左下角空白处画一个部分放大的子图
# -*- coding: utf-8 -*-
# 画放大子图
import h5py
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
# 准备数据
f = h5py.File("data.hdf5", "r")
keys = f.keys()
pulse = []
time = []
for e in f['pulse']:
pulse.append(e)
for e in f['time']:
time.append(e)
# x1 = time
# y1 = pulse
x = np.arange(len(pulse))
y = np.array(pulse)
# 绘图
fig, ax = plt.subplots(1, 1, figsize=(6, 10))
ax.plot(x, y, 'r', label='pulse') # 画线并添加图例legend
# 翻阅matplotlib的官方API手册发现ax根本没有title这个接口,正确的接口是set_title。所以,ax.title → ax.set_title
ax.set_title("Number of samples_pulse")
# 嵌入绘制局部放大图的坐标系
axins = inset_axes(ax, width="40%", height="30%", loc='lower left',
bbox_to_anchor=(0.5, 0.1, 1, 1),
bbox_transform=ax.transAxes)
# # 在子坐标系中绘制原始数据
axins.plot(x, y, 'r')
# 设置放大区间
zone_left = 2000
zone_right = 2800
# 坐标轴的扩展比例(根据实际数据调整)
x_ratio = 1.0 # x轴显示范围的扩展比例
y_ratio = 0.3 # 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(y[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)
# 建立父坐标系与子坐标系的连接线
# loc1 loc2: 坐标系的四个角
# 1 (右上) 2 (左上) 3(左下) 4(右下)
mark_inset(ax, axins, loc1=3, loc2=1, fc="none", ec='k', lw=1)
# 显示
plt.show()