Python 如何在matplotlib上获取科学记数法的乘法器字符串
我试图获取matplotlib科学符号偏移量中的文本,但是Python 如何在matplotlib上获取科学记数法的乘法器字符串,python,matplotlib,Python,Matplotlib,我试图获取matplotlib科学符号偏移量中的文本,但是get\u offset()或get\u offset\u text()返回一个空字符串。我已经检查了这些问题,但它们不起作用: 下面是一个简单的例子: 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 =
get\u offset()
或get\u offset\u text()
返回一个空字符串。我已经检查了这些问题,但它们不起作用:
下面是一个简单的例子:
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,也会发生同样的情况。我错过什么了吗?是否有单独的函数来获取乘数(而不是偏移)
编辑:我目前正在MacBook Pro上使用Python 3.9.0
和matplotlib 3.4.2
,我刚刚运行了python3 test.py
edit2:我已经安装了Python 3.9.5
,使用fig.canvas.draw()的解决方案仍然不起作用。Linux也是如此
edit3:使用MacOSX
后端时会出现问题。当更改为TkAgg
或Agg
时,get_偏移与提供的解决方案一起工作。首先需要绘制图形,使对象不保留某些默认值。从上的源代码:
只需调用fig.canvas.draw()
,然后ax.yaxis.get\u offset\u text()
将获得所需的更新值
x=np.arange(1,20)
y=np.exp(x)
图,ax=plt子批次(1,1)
轴图(x,y)
ax.yaxis.set\u major\u格式化程序(ScalarFormatter(useMathText=True))
图canvas.draw()
offset=ax.yaxis.get\u major\u formatter().get\u offset()
打印(胶印)
#$\times\mathdefault{10^{8}}\mathdefault{}$
我不确定我是否理解正确:我已经在ax.plot
下面添加了fig.canvas.draw()
,但是get\u offset
和get\u offset\u text
仍然返回空的…@Filipe调用draw()
应该在设置格式设置程序之后,请参阅我添加的代码段。我也测试了这一点,它仍然给我空白!这可能是我安装的东西吗?我在matplotlib 3.4.2中使用Python3.9.0…我在使用py 3.9.2和mpl 3.4.1,所以我认为它不会是这些版本。你是怎么策划的?可能会更新这个问题。我已经添加了,看起来确实与版本或安装有关:我在其他机器上绘制了图,我得到了预期的输出!:/
"""
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.
"""