简体   繁体   中英

How to set offset with matplotlib

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 !

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

在此处输入图片说明


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM