轴在matplotlib中标记标签填充

时间:2012-10-06 04:27:25

标签: python matplotlib

我正在尝试在Python Matplotlib中制作一个伪彩色图像图,但我对布局有一个小问题 - 轴刻度标签是非常小的数字(1e-7左右),因此Matplotlib提出了一个指数在整个轴上。这很好,但它与x轴标签和标题重叠!

See how the title overlaps with "1e-7"!

有没有更好的方法来解决这个问题,而不仅仅是向上攻击标题和向下标记xlabel(如果这是要走的路,最好的方法是什么?)我试图绘制很多使用最大代码重用的不同东西,所以如果Matplotlib有办法解决这个问题而不需要手动设置文本定位,这将是最好的!

以下是我如何生成这个情节:

fig = Figure(figsize=(5.5, 4.25))
ax = fig.add_subplot(111)
ax.set_title('The title', size=12)
ax.set_xlabel('The xlabel', size=10)
ax.set_ylabel('The Ylabel', size=10)
ax.ticklabel_format(scilimits=(-3,3))

pcm = ax.pcolor(X, Y, Z, cmap=cm.jet) #X,Y is a meshgrid and Z is the function evaluated on it
ax.get_figure().colorbar(pcm, ax=ax, use_gridspec=True)
ax.set_axes([0, 1e-3, -5e-7, 5e-7])

#Some code for the hatching at the top and bottom of the plot

for ticklabel in ax.get_xticklabels():
    ticklabel.set_size(8)
for ticklabel in ax.get_yticklabels():
    ticklabel.set_size(8)
ax.get_xaxis().get_offset_text().set_size(8)
ax.get_yaxis().get_offset_text().set_size(8)
fig.subplots_adjust()
c = FigureCanvas(fig)
c.print_figure('filename.png', dpi=300)

1 个答案:

答案 0 :(得分:4)

最简单的方法是通过将X和Y乘以1e3和1e7来消除对指数的需要:

pcm = ax.pcolor(X*1e3, Y*1e7, Z, cmap=cm.jet)

然后将标签更改为:

ax.set_xlabel('Longitudinal distance across waveguide ($10^{-3}$ m)', size=10)
ax.set_ylabel('Transverse distance across waveguide ($10^{-7}$ m)', size=10)

您也可以直接更改刻度标签或使用matplotlib.ticker.Formatter,但前者稍微繁琐而后者则过度。