如何在Matplotlib中统一坐标轴范围并保留边距
解决Matplotlib子图统一Y轴范围且保留边距的问题
你在绘制左右两个散点子图时会遇到这个矛盾:
- 不手动设置Y轴范围时,Matplotlib自动添加边距避免数据点被截断,但两个子图的Y轴范围不一致;
- 手动统一Y轴范围后,默认边距消失,部分数据点会被坐标轴截断。
下面提供两种实用的解决方案:
方法一:手动计算带边距的统一范围
先获取所有Y轴数据的极值,再给极值加上固定比例的边距,最后将这个带边距的范围应用到两个子图。这种方法可以精确控制边距大小。
import pandas as pd import matplotlib.pyplot as plt import numpy as np data = { 'id': [1, 2, 3, 4, 5,6,7,8,9,10], 'LeftError': [0.1, 0.2, 0.15, 0.3, 0.25,-0.1, -0.2, -0.15, -0.3, -0.25], 'RightError': [0.2, 0.3, 0.25, 0.4, 0.35,-0.2, -0.3, -0.25, -0.4, -0.35], 'NCL': [1, 2, 1, 3, 2,-1, -2, -1, -3, -2], 'NCR': [2, 3, 2, 4, 3,-2, -3, -2, -4, -3], } df = pd.DataFrame(data) fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # 绘制左右子图 axes[0].scatter(df['NCL'], df['LeftError'], color='blue') axes[0].set_xlabel('NCL') axes[0].set_ylabel('Left Error') axes[1].scatter(df['NCR'], df['RightError'], color='green') axes[1].set_xlabel('NCR') axes[1].set_ylabel('Right Error') # 合并所有Y轴数据,计算极值 all_y = pd.concat([df['LeftError'], df['RightError']]) y_min, y_max = all_y.min(), all_y.max() # 计算边距:取数据范围的5%作为上下边距,若数据无波动则用固定边距 y_range = y_max - y_min margin = y_range * 0.05 if y_range != 0 else 0.1 # 设置统一的Y轴范围(包含边距) unified_ylim = (y_min - margin, y_max + margin) axes[0].set_ylim(unified_ylim) axes[1].set_ylim(unified_ylim) plt.tight_layout() plt.show()
方法二:复用Matplotlib自动计算的边距
先让两个子图各自自动计算带边距的范围,再取两个范围的并集作为统一范围。这种方法和Matplotlib默认的边距逻辑一致,无需手动调整比例。
import pandas as pd import matplotlib.pyplot as plt import numpy as np data = { 'id': [1, 2, 3, 4, 5,6,7,8,9,10], 'LeftError': [0.1, 0.2, 0.15, 0.3, 0.25,-0.1, -0.2, -0.15, -0.3, -0.25], 'RightError': [0.2, 0.3, 0.25, 0.4, 0.35,-0.2, -0.3, -0.25, -0.4, -0.35], 'NCL': [1, 2, 1, 3, 2,-1, -2, -1, -3, -2], 'NCR': [2, 3, 2, 4, 3,-2, -3, -2, -4, -3], } df = pd.DataFrame(data) fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # 绘制左右子图 axes[0].scatter(df['NCL'], df['LeftError'], color='blue') axes[0].set_xlabel('NCL') axes[0].set_ylabel('Left Error') axes[1].scatter(df['NCR'], df['RightError'], color='green') axes[1].set_xlabel('NCR') axes[1].set_ylabel('Right Error') # 让两个子图自动计算带边距的范围 axes[0].autoscale() axes[1].autoscale() # 获取两个子图的Y轴范围,取并集作为统一范围 y0_min, y0_max = axes[0].get_ylim() y1_min, y1_max = axes[1].get_ylim() unified_min = min(y0_min, y1_min) unified_max = max(y0_max, y1_max) # 应用统一范围到两个子图 axes[0].set_ylim(unified_min, unified_max) axes[1].set_ylim(unified_min, unified_max) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者KansaiRobot
相关产品推荐
相关产品推荐

