P-M
P-M

Reputation: 1399

Matplotlib axis label move scientific exponent into same line

I am currently producing a plot which on the x-axis ranges from 0 to 1.3e7. I am plotting this as follows:

plt.errorbar(num_vertices,sampled_ave_path_average,yerr=sampled_ave_path_stdev,fmt='.',markersize='1',capsize=2,capthick=2)
plt.xlabel('Number of vertices')
plt.ylabel('Average shortest path length')
plt.xlim(0,1.3*10**7)
plt.savefig('path_length_vs_N.eps', bbox_inches='tight')
plt.savefig('path_length_vs_N.png', bbox_inches='tight')
plt.close()

This produces a plot where the x-axis tick labels are in scientific notation which is what I would like. I was however wondering whether it is possible to move the 1e7 (circled in red below) onto the same line as the other labels? (I realise this could cause confusion about the exponents of the other values.)

output of plot routine showing location of scientific exponent marker

Upvotes: 2

Views: 6268

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339200

First, you may look at the following questions:

The first one may be a possible alternative (because you mention that the envisioned solution "might cause confusion about the exponents"). The second might point a way to a possible solution although it is about using a colorbar.

So in order to change the position of the offset text to be in line with the xtick labels, the following would be a way to go.

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

x = np.linspace(1e7, 9e7)
y = 1-np.exp(-np.linspace(0,5))
fig, ax = plt.subplots()
ax.plot(x,y)


pad = plt.rcParams["xtick.major.size"] + plt.rcParams["xtick.major.pad"]
def bottom_offset(self, bboxes, bboxes2):
    bottom = self.axes.bbox.ymin
    self.offsetText.set(va="top", ha="left") 
    oy = bottom - pad * self.figure.dpi / 72.0
    self.offsetText.set_position((1, oy))

ax.xaxis._update_offset_text_position = types.MethodType(bottom_offset, ax.xaxis)

plt.show()

enter image description here

Upvotes: 3

Related Questions