0

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)

Correct precision, wrong tick positions

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?

Wrong precision, correct tick positions

Kevin Liu
  • 378
  • 2
  • 13

3 Answers3

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

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

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)

enter image description here

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

Kevin Liu
  • 378
  • 2
  • 13
0

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.

Xenon
  • 111
  • 1
  • 4