Gre*_*ory 7 label axes matplotlib python-2.7
我试图将轴固定为两个不同数据集的科学记数,其中一个是[1-9] x1e-3,另一个是[1-9] x1e-4.我想将两个轴设置为10 ^ -4并且在十进制之后具有一位数(例如%.1e).这是一个我试图玩的简单版本:我希望轴上的数字至少为1,我希望两种力量都相同.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1,9,9)
y1 = x*10**(-4)
y2 = x*10**(-3)
fig, ax = plt.subplots(2,1,sharex=True)
ax[0].plot(x,y1)
ax[0].ticklabel_format(axis='y', style='sci', scilimits=(-4,-4))
ax[0].yaxis.major.formatter._useMathText = True
ax[1].plot(x,y2)
ax[1].ticklabel_format(axis='y', style='sci', scilimits=(-4,-4))
ax[1].yaxis.major.formatter._useMathText = True
plt.show()
Run Code Online (Sandbox Code Playgroud)
您可以matplotlib.ticker.ScalarFormatter
将orderOfMagnitude
属性子类化并修复为您喜欢的数字(在本例中-4
).
以同样的方式,您可以修复要使用的格式.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker
class OOMFormatter(matplotlib.ticker.ScalarFormatter):
def __init__(self, order=0, fformat="%1.1f", offset=True, mathText=True):
self.oom = order
self.fformat = fformat
matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText)
def _set_orderOfMagnitude(self, nothing):
self.orderOfMagnitude = self.oom
def _set_format(self, vmin, vmax):
self.format = self.fformat
if self._useMathText:
self.format = '$%s$' % matplotlib.ticker._mathdefault(self.format)
x = np.linspace(1,9,9)
y1 = x*10**(-4)
y2 = x*10**(-3)
fig, ax = plt.subplots(2,1,sharex=True)
ax[0].plot(x,y1)
ax[1].plot(x,y2)
for axe in ax:
axe.yaxis.set_major_formatter(OOMFormatter(-4, "%1.1f"))
axe.ticklabel_format(axis='y', style='sci', scilimits=(-4,-4))
plt.show()
Run Code Online (Sandbox Code Playgroud)
虽然这可能第一眼看起来很复杂它确实的唯一事情是覆盖私有方法_set_orderOfMagnitude
和_set_format
,从而防止他们是我们不希望的背景做一些复杂的东西.因为在最后,我们需要的是,独立的内部是什么情况,self.orderOfMagnitude
始终-4
和self.format
永远"%1.1f"
.
归档时间: |
|
查看次数: |
4219 次 |
最近记录: |