You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用twinx和twiny时,如何为坐标轴添加1前7后的边距?

解决Matplotlib散点图轴刻度无侧边空白的问题

问题描述

使用Matplotlib创建带双坐标轴(twinx/twiny)的散点图时,x、y轴的刻度1左侧和7右侧没有预留空白空间,图表内容紧贴轴边缘;而目标效果要求刻度与轴边缘之间有明显的空白间隔。

解决方案

问题根源是轴的显示范围默认与刻度范围完全重合(1到7),只需手动设置轴的显示范围,给两端留出额外空间即可。需要注意主坐标轴和所有副坐标轴都要同步设置范围,避免轴刻度错位。

具体操作:

  • 使用set_xlim()和set_ylim()方法,将轴范围设为比刻度范围稍宽的区间,比如(0.8, 7.2)(可根据需求调整余量大小)
  • 对所有主、副坐标轴执行此设置,包括twiny/twinx创建的额外轴

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt

# 设置画布大小并创建子图
fig, axes = plt.subplots(2,1, figsize=(6, 12))

# 生成随机数据
num_points = 24
x = np.random.normal(4, 1.5, num_points)
y = np.random.normal(4, 1.5, num_points)
sizes = np.random.uniform(50, 200, num_points)
colors = np.random.rand(num_points, 3)

# 创建散点图
for ax in axes:
    ax.scatter(x, y, s=sizes, c=colors, alpha=0.7, edgecolors='k', linewidths=1)

# 设置主坐标轴刻度,并统一设置轴范围(预留空白)
axis_range = (0.8, 7.2)
for ax in axes:
    ax.set_xticks(np.arange(1, 8))
    ax.set_yticks(np.arange(1, 8))
    ax.set_xticklabels([str(i) for i in range(1, 8)])
    ax.set_yticklabels([str(i) for i in range(1, 8)])
    # 设置主轴范围
    ax.set_xlim(axis_range)
    ax.set_ylim(axis_range)

# 处理顶部子图的双坐标轴
axes2 = axes[0].twinx()
axes2.set_ylabel('Y-axis 2 (Top)')
axes2.set_yticks(np.arange(1, 8))
# 同步副Y轴范围
axes2.set_ylim(axis_range)

axes2x = axes[0].twiny()
axes2x.set_xlabel('X-axis 2 (Top)')
axes2x.set_xticks(np.arange(1, 8))
# 同步副X轴范围
axes2x.set_xlim(axis_range)

# 隐藏顶部子图的主X轴
axes[0].get_xaxis().set_visible(False)
axes[0].set_xlabel('')

# 处理底部子图的坐标轴
axes[1].set_xlabel('X-axis 1 (Bottom)')
axes[1].set_ylabel('Y-axis 1 (Bottom)')

# 底部子图的副Y轴
axes2y = axes[1].twinx()
axes2y.set_ylabel('Y-axis 2 (Bottom)')
axes2y.set_yticks(np.arange(1, 8))
# 同步副Y轴范围
axes2y.set_ylim(axis_range)

# 设置标题
axes[1].set_title('Bottom Scatter Plot')

plt.show()

说明

通过统一设置所有坐标轴的显示范围,让刻度1和7与轴边缘之间产生空白,同时保证主副轴的刻度对齐,符合目标效果的边距要求。你可以根据实际需求调整axis_range的数值,控制空白的大小。

内容的提问来源于stack exchange,提问作者koko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:30:06