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

如何在seaborn/matplotlib单张图表中设置不同区段的x轴刻度间隔

实现方案

你可以手动生成分段符合间隔要求的刻度列表,再通过FixedLocator绑定到x轴即可,修改后的完整代码如下:

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

f, ax = plt.subplots(figsize=(15,7))
sns.despine(bottom=True, left=True)

sns.boxplot(x=x)
ax.set(xlim=(0, 120))
ax.grid(linestyle='-', axis="x")

# 生成分段刻度:24及以前间隔8,24以后间隔24
ticks_low = np.arange(0, 25, 8)
ticks_high = np.arange(48, 121, 24)
custom_ticks = np.concatenate([ticks_low, ticks_high])
ax.xaxis.set_major_locator(ticker.FixedLocator(custom_ticks))

ax.set_axisbelow(True)
plt.show()

上述代码生成的x轴刻度依次为0,8,16,24,48,72,96,120,完全符合你要求的分段间隔规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:54:03