Set precision on custom ticks with scientific style

与世无争的帅哥 提交于 2021-02-11 12:20:34

问题


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?


回答1:


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()




回答2:


I managed to solve the issue by manually specifying the scientific limits and then creating custom labels:

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)

This solves the issue though it requires manually specifying the exponent.




回答3:


A simple way to do this is to round the x values in the ticks assignment:

plt.xticks(np.round(x,decimals=6))

works for me for example.

Note that this will actually move the ticks to the indicated positions. With only one decimal this will be clearly visible.



来源:https://stackoverflow.com/questions/54869298/set-precision-on-custom-ticks-with-scientific-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!