1

I'm trying to remove the offset that matplotlib automatically put on my graphs. For example, with the following code:

x=np.array([1., 2., 3.])
y=2.*x*1.e7
MyFig = plt.figure()
MyAx = MyFig.add_subplot(111)
MyAx.plot(x,y)

I obtain the following result (sorry, I cannot post image): the y-axis have the ticks 2, 2.5, 3, ..., 6, with a unique "x10^7" at the top of the y axis.

I would like to remove the "x10^7" from the top of the axis, and making it appearing with each tick (2x10^7, 2.5x10^7, etc...). If I understood well what I saw in other topics, I have to play with the use_Offset variable. So I tried the following thing:

MyFormatter = MyAx.axes.yaxis.get_major_formatter()
MyFormatter.useOffset(False)
MyAx.axes.yaxis.set_major_formatter(MyFormatter)

without any success (result unchanged). Am I doing something wrong? How can I change this behaviour? Or have I to manually set the ticks ?

Thanks by advance for any help !

user1618164
  • 15
  • 1
  • 3
  • Could you post the link to the other topics you have found? Personally I think you would be better of rescaling the axis and including that in the axis labels. – Greg Jul 17 '13 at 09:49
  • 1
    you can define the axis ticks manually. Have a look at [this answer](http://stackoverflow.com/questions/17426283/axis-labelling-with-matplotlib-too-sparse/17426515#17426515) or [this one](http://stackoverflow.com/questions/16529038/matplotlib-tick-axis-notation-with-superscript/16530841#16530841) – ala Jul 17 '13 at 10:14
  • Ok, thanks for the answer. I will thus set them manually when I need particular formatting ! – user1618164 Jul 17 '13 at 11:00

1 Answers1

1

You can use the FuncFormatter from the ticker module to format the ticklabels as you please:

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

x=np.array([1., 2., 3.])
y=2.*x*1.e7

MyFig = plt.figure()
MyAx = MyFig.add_subplot(111)

def sci_notation(x, pos):
    return "${:.1f} \\times 10^{{6}}$".format(x / 1.e7)

MyFormatter = FuncFormatter(sci_notation)

MyAx.axes.yaxis.set_major_formatter(MyFormatter)

MyAx.plot(x,y)

plt.show()

enter image description here


On a side note; the "x10^7" value that appears at the top of your axis is not an offset, but a factor used in scientific notation. This behavior can be disabled by calling MyFormatter.use_scientific(False). Numbers will then be displayed as decimals.

An offset is a value you have to add (or subtract) to the tickvalues rather than multiply with, as the latter is a scale.

For reference, the line

MyFormatter.useOffset(False)

should be

MyFormatter.set_useOffset(False)

as the first one is a bool (can only have the values True or False), which means it can not be called as a method. The latter is the method used to enable/disable the offset.

sodd
  • 12,482
  • 3
  • 54
  • 62