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

如何使用Matplotlib仅偏移单个坐标轴刻度解决重叠问题

Matplotlib坐标轴刻度标签重叠问题(添加空格无效的解决方法)

问题描述

我用Matplotlib绘制图表时,自定义了部分坐标轴刻度,但出现了刻度标签重叠的情况。尝试在刻度标签字符串末尾添加空格来调整间距,却发现所有空格都被忽略了。以下是我试过但无效的代码:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

rc_fonts = {
   'text.usetex': True,
   'font.size': 20,
   'font.family': 'serif',
   'font.serif': 'cm'
}
mpl.rcParams.update(rc_fonts)

x = np.linspace(0, 1, 100, endpoint=True)
y = x**2

labels = ['0',r'$\varepsilon$', '1']
tested_labels1 = ['0',r'$\varepsilon$   ', '1']
tested_labels2 = ['0',r'$\varepsilon$\\ \\ \\ \\qquad', '1']
tested_labels3 = ['0',r'$\varepsilon\qquad$   ', '1']
x_labels = [0, 0.03, 1]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_yticks(x_labels, labels)
# 以下尝试均无效——空格被忽略
#ax.set_yticks(x_labels, tested_labels1)
#ax.set_yticks(x_labels, tested_labels2)
#ax.set_yticks(x_labels, tested_labels3)

plt.show()

问题效果

解决方案

在Matt Pitkin的帮助下,我找到了可行的解决方法(虽然不像加空格那么简便,但确实有效),具体代码如下:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

rc_fonts = {
    'text.usetex': True,
    'font.size': 20,
    'font.family': 'serif',
    'font.serif': 'cm'
}
mpl.rcParams.update(rc_fonts)

x = np.linspace(0, 1, 100, endpoint=True)
y = x**2

labels = ['0',r'$\varepsilon$', '1']
x_labels = [0, 0.03, 1]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_yticks(x_labels, labels)

dx = -0.15; dy = 0. 
offset = mpl.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
ax.yaxis.get_majorticklabels()[1].set_transform(ax.yaxis.get_majorticklabels()[1].get_transform() + offset)

plt.show()

解决效果


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:15:50