[英]How to get multiplier string of scientific notation on matplotlib
我试图在 matplotlib 的科学计数法的偏移量中获取文本,但get_offset()
或get_offset_text()
返回一个空字符串。 我检查了这些问题,但没有奏效:
如何将y轴比例因子移动到y轴label旁边的position?
这是一个简单的例子:
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()
我想得到x10^8
,但它只返回:
Text(0, 0.5, '')
如果我不使用 ScalarFormatter,也会发生同样的情况。 我错过了什么吗? 是否有单独的 function 来获得乘数(而不是偏移量)?
编辑:我目前在 MacBook Pro 上使用Python 3.9.0
和matplotlib 3.4.2
,我只是运行python3 test.py
。
编辑2 :我已经安装了Python 3.9.5
, fig.canvas.draw()
的解决方案仍然不起作用。 Linux 的工作原理相同。
edit3:使用MacOSX
后端时会出现问题。 当更改为TkAgg
或Agg
时, get_offset 与提供的解决方案一起使用。
您首先需要为 object 绘制图形以不保留一些默认值。 从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.
"""
只需调用fig.canvas.draw()
然后ax.yaxis.get_offset_text()
将获得您想要的更新值。
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{}$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.