以科学风格设置自定义刻度的精度 [英] Set precision on custom ticks with scientific style
本文介绍了以科学风格设置自定义刻度的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已生成此代码以生成以下图表:
将matplotlib.pyplot导入为plt将numpy导入为npx = np.linspace(1/10000, 1/2000, 13)y = x ** 2plt.plot(x,y,'ro')plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), useMathText=True)
我想在数据的位置设置xticks.如果再执行 plt.xticks(x,rotation = 45)
,我会在所需的位置获得刻度,但是小数点太多(请参见下图).如何在指定位置获得刻度,但精度可控?
解决方案
为了获得刻度标签的预定义格式同时保持科学乘数,您可以使用 的简化版本我在
I have produced this code to generate the following graph:
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)
I would like to set the xticks at the position of the data. If I then do plt.xticks(x, rotation=45)
I get the ticks at the desired locations but with too many decimal places (see next picture). How do I get the ticks at the specified locations but with a controllable precision?
解决方案
In order to get a predefined format for the ticklabels while maintaining the scientific multiplier you can use a simplified version of the OOMFormatter
from my answer here.
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()
这篇关于以科学风格设置自定义刻度的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文