I have some data plotted which I force to scientific notation to powers of 10 (instead of exponential). Heres a snippet of the code:
import matplotlib.ticker as mticker
formatter = mticker.ScalarFormatter(useMathText=True)
formatter.set_powerlimits((-3,2))
ax.yaxis.set_major_formatter(formatter)
However, the scale factor of x10^-4 appears on the top left hand corner of the graph.
Is there a simple method to force the position of this scale factor next to the y label as I have illustrated in the diagram below?
You may set the offset to invisible, such that it does not appear in its original position.
ax.yaxis.offsetText.set_visible(False)
You may then get the offset from the formatter an update the label with it
offset = ax.yaxis.get_major_formatter().get_offset()
ax.yaxis.set_label_text("original label" + " " + offset)
such that it appears inside the label.
The following automates this using a class with a callback, such that if the offset changes, it will be updated in the label.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
class Labeloffset():
def __init__(self, ax, label="", axis="y"):
self.axis = {"y":ax.yaxis, "x":ax.xaxis}[axis]
self.label=label
ax.callbacks.connect(axis+'lim_changed', self.update)
ax.figure.canvas.draw()
self.update(None)
def update(self, lim):
fmt = self.axis.get_major_formatter()
self.axis.offsetText.set_visible(False)
self.axis.set_label_text(self.label + " "+ fmt.get_offset() )
x = np.arange(5)
y = np.exp(x)*1e-6
fig, ax = plt.subplots()
ax.plot(x,y, marker="d")
formatter = mticker.ScalarFormatter(useMathText=True)
formatter.set_powerlimits((-3,2))
ax.yaxis.set_major_formatter(formatter)
lo = Labeloffset(ax, label="my label", axis="y")
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With