0

When I run this

import numpy as np
import matplotlib.pyplot as plt

plt.plot(np.arange(1e6, 3 * 1e7, 1e6))

I get this plot plot_before,

where the y-axis is a bit weird (there is a 1e7 on the top).

So, I am trying to fix this. I came up with a solution using FuncFormatter,

import numpy as np
import matplotlib.pyplot as plt

plt.plot(np.arange(1e6, 3 * 1e7, 1e6))
def y_fmt(x, y):
    if x == 0:
        return r'$0$'
    
    r, p = "{:.1e}".format(x).split('e+')
    r = r[:-2] if r[-1] == '0' else r
    p = p[1:] if p[0] == '0' else p
    
    return r'${:}\times10^{:}$'.format(r, p)

plt.gca().get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(y_fmt))

here is the result plot_after.

My question is, is there a better way of doing this, maybe using LogFormatterSciNotation? Or is it possible to say matplotlib to not put 1e7 on the top?

UPDATE:

I didn’t know that there is such a thing as

plt.ticklabel_format(useOffset=False)

but it seems that this is not doing anything for the data I used above (np.arange(1e6, 3 * 1e7, 1e6)). I don’t know if this is a bug or if there is something I don’t understand about this function...

Arto
  • 1
  • 1

1 Answers1

0

You may want ScalarFormatter and ticklabel_format. Some claimed you need both two of them, or just ScalarFormatter and don't need ticklabel_format. I'm not entirely sure about this behaviour. But it works.

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

fig, ax = plt.subplots(1,1)
ax.plot(np.arange(1e6, 3 * 1e7, 1e6))
ax.yaxis.set_major_formatter(mt.ScalarFormatter(useMathText=True))
ax.ticklabel_format(style="sci", axis="y", scilimits=(0,2))  

ex

atommy
  • 58
  • 4
  • Thanks for your answer, but in your example, there is _x10^7_ on the top. I want it to be on the left with y-ticks. – Arto Oct 12 '22 at 13:20
  • @Arto I see. My bad. Then I don't come up with an easy way to do it. I would use `FuncFormatter` like you did. – atommy Oct 12 '22 at 18:48