我有一些数据绘制,我强制科学记数法的权力为10(而不是指数).下面是一段代码:
import matplotlib.ticker as mticker
formatter = mticker.ScalarFormatter(useMathText=True)
formatter.set_powerlimits((-3,2))
ax.yaxis.set_major_formatter(formatter)
Run Code Online (Sandbox Code Playgroud)
但是,x10 ^ -4的比例因子出现在图的左上角.
是否有一种简单的方法可以强制将此比例因子的位置放在y标签旁边,如下图所示?
您可以将偏移设置为不可见,以使其不会出现在其原始位置.
ax.yaxis.offsetText.set_visible(False)
Run Code Online (Sandbox Code Playgroud)
然后,您可以从格式化程序获取偏移量,并使用它更新标签
offset = ax.yaxis.get_major_formatter().get_offset()
ax.yaxis.set_label_text("original label" + " " + offset)
Run Code Online (Sandbox Code Playgroud)
这样它就出现在标签内.
下面使用带回调的类自动执行此操作,这样如果偏移更改,它将在标签中更新.
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2032 次 |
| 最近记录: |