Issue
I'm trying to get the text in the offset of the scientific notation of matplotlib, but get_offset()
or get_offset_text()
returns an empty string. I have checked these questions, but they didn't work:
How to move the y axis scale factor to the position next to the y axis label?
Adjust exponent text after setting scientific limits on matplotlib axis
prevent scientific notation in matplotlib.pyplot
Here is a simple example:
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
import numpy as np
x = np.arange(1,20)
y = np.exp(x)
fig,ax = plt.subplots(1,1)
ax.plot(x,y)
ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
print(ax.yaxis.get_offset_text())
print(ax.yaxis.get_major_formatter().get_offset())
fmt = ax.yaxis.get_major_formatter()
offset = ax.yaxis.get_major_formatter().get_offset()
print(offset)
plt.show()
I'd like to get the x10^8
, but it returns only:
Text(0, 0.5, '')
The same happens if I don't use the ScalarFormatter. Am I missing something? Is there a separate function to get the multiplier (instead of the offset)?
edit: I'm currently using Python 3.9.0
with matplotlib 3.4.2
on a MacBook Pro, and I just run python3 test.py
.
edit2: I have installed Python 3.9.5
, and the solution with fig.canvas.draw()
still does not work. The same with Linux works.
edit3: The problem happens when using the MacOSX
backend. When changing to TkAgg
or Agg
, the get_offset works with the provided solution.
Solution
You first need to draw the figure for the object to not hold some default values. From the source code on FigureCanvasBase.draw
:
"""
Render the `.Figure`.
It is important that this method actually walk the artist tree
even if not output is produced because this will trigger
deferred work (like computing limits auto-limits and tick
values) that users may want access to before saving to disk.
"""
Simply call fig.canvas.draw()
and then ax.yaxis.get_offset_text()
will have the updated values you want.
x = np.arange(1, 20)
y = np.exp(x)
fig, ax = plt.subplots(1, 1)
ax.plot(x, y)
ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
fig.canvas.draw()
offset = ax.yaxis.get_major_formatter().get_offset()
print(offset)
# $\times\mathdefault{10^{8}}\mathdefault{}$
Answered By - Reti43
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.