3

I work on a plot in python using the matplot library. The numbers which I have to generate are very big, so also the ticks on the axes are a large numbers and take a lot of space. I was trying to present them as a powers (for example instead having a tick 100000000 I want to have 10^8). I used command: ax.ticklabel_format(style='sci', axis='x', scilimits=(0,4)) however this only created something like this

enter image description here

Is there any other solution to have ticks for the plot as: 1 x 10^4, 2 x 10^4, etc or write the value 1e4 as 10^4 at the end of the label's ticks?

Ziva
  • 3,181
  • 15
  • 48
  • 80

2 Answers2

6

You can use the matplotlib.ticker module, and set the ax.xaxis.set_major_formatter to a FuncFormatter.

For example:

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

plt.rcParams['text.usetex'] = True

fig,ax = plt.subplots(1)

x = y = np.arange(0,1.1e4,1e3)
ax.plot(x,y)

def myticks(x,pos):

    if x == 0: return "$0$"

    exponent = int(np.log10(x))
    coeff = x/10**exponent

    return r"${:2.0f} \times 10^{{ {:2d} }}$".format(coeff,exponent)

ax.xaxis.set_major_formatter(ticker.FuncFormatter(myticks))

plt.show()

enter image description here

Note, this uses LaTeX formatting (text.usetex = True) to render exponents in the tick labels. Also note the double braces required to differentiate the LaTeX braces from the python format string braces.

tmdavison
  • 64,360
  • 12
  • 187
  • 165
1

There might be a better solution, but if you know the values of each xtick, you can also manually name them. Here is an example: http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

Dremet
  • 1,008
  • 1
  • 9
  • 23