如何放大Matplotlib图表局部并嵌入至同一张绘图顶部?
Matplotlib实现图表局部放大并添加关联连线
核心实现思路
- 创建主坐标轴绘制原始数据曲线
- 在主图顶部嵌入放大子坐标轴,聚焦指定区域(x轴全范围、y轴-3至15)
- 在主图上用红色矩形标记放大区域,通过连线关联放大图与原图对应位置
完整代码示例
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes from matplotlib.patches import ConnectionPatch import numpy as np # 模拟原问题中的数据分布 x = np.linspace(0, 10, 100) y = np.where(x < 5, np.random.randn(100)*2 + 5, np.random.randn(100)*10 + 50) # 创建主图表 fig, ax = plt.subplots(figsize=(10, 6)) ax.plot(x, y, 'b-', label='原始数据') # 定义放大区域范围 x_inset_range = [x.min(), x.max()] y_inset_range = [-3, 15] # 在主图顶部生成放大子图 ax_inset = inset_axes(ax, width="100%", height="30%", loc='upper center', bbox_to_anchor=(0, 1.05, 1, 1), bbox_transform=ax.transAxes) # 在子图中绘制放大区域的数据 ax_inset.plot(x, y, 'b-') ax_inset.set_xlim(x_inset_range) ax_inset.set_ylim(y_inset_range) ax_inset.tick_params(axis='x', labelbottom=False) # 隐藏重复的x轴刻度 ax_inset.set_ylabel('放大区域') # 在主图上标记放大区域的矩形框 rect = plt.Rectangle((x_inset_range[0], y_inset_range[0]), x_inset_range[1]-x_inset_range[0], y_inset_range[1]-y_inset_range[0], fill=False, edgecolor='red', linewidth=2) ax.add_patch(rect) # 添加连线关联放大图与原图区域 conn_left = ConnectionPatch(xyA=(x_inset_range[0], y_inset_range[1]), xyB=(x_inset_range[0], y_inset_range[0]), coordsA=ax.transData, coordsB=ax_inset.transData, color='red', linestyle='--', linewidth=1.5) conn_right = ConnectionPatch(xyA=(x_inset_range[1], y_inset_range[1]), xyB=(x_inset_range[1], y_inset_range[0]), coordsA=ax.transData, coordsB=ax_inset.transData, color='red', linestyle='--', linewidth=1.5) fig.add_artist(conn_left) fig.add_artist(conn_right) # 主图基础设置 ax.set_xlabel('X轴') ax.set_ylabel('Y轴') ax.legend() plt.tight_layout() plt.show()
代码关键说明
- 放大子图创建:通过
inset_axes控制子图的位置(主图顶部)和尺寸,bbox_to_anchor参数精准定位子图相对主图的位置 - 区域标记:用
Rectangle在主图画出放大区域的范围,直观展示待放大的位置 - 关联连线:借助
ConnectionPatch建立主图矩形框与放大子图的视觉连接,明确两者的对应关系 - 细节优化:隐藏放大子图的x轴刻度,避免与主图重复;用
tight_layout()自动调整布局,防止元素重叠
内容的提问来源于stack exchange,提问作者Fadil
相关产品推荐
相关产品推荐

