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

如何用plt.xlim或其他方法放大Matplotlib散点图的密集数据区?

解决Matplotlib散点图密集区域放大+稀疏区大间距刻度的方法

当然可以实现,核心思路是手动控制X轴的显示范围和刻度位置,让密集区域(200-500)的刻度更密集(视觉上放大),稀疏区域的刻度保持大间距。下面是两种实用方法:

方法1:手动设置刻度+调整显示范围

直接通过plt.xticks()自定义刻度位置,配合plt.xlim()控制整体显示范围,操作简单直观:

import matplotlib.pyplot as plt
import numpy as np

# 模拟图像宽高数据(多数集中在200-500)
np.random.seed(42)
widths = np.concatenate([
    np.random.randint(0, 200, 100),
    np.random.randint(200, 500, 800),
    np.random.randint(500, 1500, 100)
])
heights = np.random.randint(100, 1200, len(widths))

plt.scatter(widths, heights)
# 设置X轴整体显示范围(包含稀疏区)
plt.xlim(0, 1500)
# 自定义刻度:稀疏区(0-200、500以上)间距大,密集区(200-500)间距小
plt.xticks([0, 200, 300, 400, 500, 1000, 1500])

plt.xlabel('图像宽度')
plt.ylabel('图像高度')
plt.title('图像宽高分布')
plt.show()

如果想进一步放大200-500区域,可以缩小X轴显示范围(比如plt.xlim(0, 600)),让密集区占据更多画布空间,同时保留稀疏区的关键刻度。

方法2:用FixedLocator精准控制刻度

如果需要更灵活的刻度定制(比如不同区间的刻度密度差异更大),可以用matplotlib.ticker.FixedLocator指定刻度位置:

import matplotlib.pyplot as plt
import numpy as np

# 模拟数据同上
np.random.seed(42)
widths = np.concatenate([
    np.random.randint(0, 200, 100),
    np.random.randint(200, 500, 800),
    np.random.randint(500, 1500, 100)
])
heights = np.random.randint(100, 1200, len(widths))

fig, ax = plt.subplots()
ax.scatter(widths, heights)

# 设置X轴范围
ax.set_xlim(0, 1500)
# 精准定义刻度位置:密集区每50一个刻度,稀疏区大间距
ax.xaxis.set_major_locator(plt.FixedLocator([0, 200, 250, 300, 350, 400, 450, 500, 1000, 1500]))
# 可选:自定义刻度标签(和位置一致时可省略)
ax.xaxis.set_major_formatter(plt.FixedFormatter([0, 200, 250, 300, 350, 400, 450, 500, 1000, 1500]))

ax.set_xlabel('图像宽度')
ax.set_ylabel('图像高度')
ax.set_title('图像宽高分布')
plt.show()

这种方式可以让密集区的刻度更精细,视觉放大效果更显著,同时稀疏区的刻度间距保持较大,不会显得拥挤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:47:28