Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用科学样式设置自定义刻度的精度_Python_Matplotlib - Fatal编程技术网

Python 使用科学样式设置自定义刻度的精度

Python 使用科学样式设置自定义刻度的精度,python,matplotlib,Python,Matplotlib,我已生成此代码以生成以下图形: import matplotlib.pyplot as plt import numpy as np x = np.linspace(1/10000, 1/2000, 13) y = x**2 plt.plot(x, y, 'ro') plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useMathText=True) 我想在数据的位置设置XTICK。如果我接着执行plt.xticks(x

我已生成此代码以生成以下图形:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1/10000, 1/2000, 13)
y = x**2
plt.plot(x, y, 'ro')
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useMathText=True)

我想在数据的位置设置XTICK。如果我接着执行
plt.xticks(x,rotation=45)
我会在所需的位置获得刻度,但小数点太多(参见下图)。如何在指定的位置以可控的精度获取刻度


我通过手动指定科学极限,然后创建自定义标签,设法解决了这个问题:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1/10000, 1/2000, 13)
y = x**2
e = 4

plt.plot(x, y, 'ro')
# plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useMathText=True)
plt.xticks(x, ['{:.1f}'.format(10**e*s) for s in x])
plt.text(1.01, 0, 'x$10^{{:d}}$'.format(e), transform=plt.gca().transAxes)


这就解决了这个问题,尽管它需要手动指定指数。

一个简单的方法是在记号赋值中对x值进行四舍五入:

plt.xticks(np.round(x,decimals=6))
例如,对我有效


请注意,这实际上会将记号移动到指定的位置。只有一个小数点,这将是清晰可见的

为了在保持科学乘数的同时获得标签的预定义格式,您可以使用我的答案中的简化版
OOMFormatter

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker

class FFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, fformat="%1.1f", offset=True, mathText=True):
        self.fformat = fformat
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText)
    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/10000, 1/2000, 13)
y = x**2
plt.plot(x, y, 'ro')
plt.xticks(x, rotation=45)

fmt = plt.gca().xaxis.set_major_formatter(FFormatter(fformat="%1.1f"))
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useMathText=True)

plt.show()