简体   繁体   中英

Axes tick label padding in matplotlib

I'm trying to make a pseudocolour image plot in Python Matplotlib, but I'm having a small problem with the layout- the axes tick labels are very small numbers (1e-7 or so), so Matplotlib puts an exponent on the entire axis. This is good, but it overlaps with the x axis label and the title!

看看标题如何与“ 1e-7”重叠!

Is there a better way to fix this other than just hacking the title upwards and the xlabel downwards (and if this is the way to go, what's the best way to do this?) I'm trying to plot a lot of different things with maximal code reuse, so if Matplotlib has a way to fix this without channging text positioning manually that would be the best!

Here's how I'm generating this plot:

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)

The easiest approach is to remove the need for the exponents by multiplying X and Y by 1e3 and 1e7:

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

then changing the labels to something like:

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

You can also change the tick labels directly or use matplotlib.ticker.Formatter but the former is slightly more tedious while the latter is overkill.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM