goodvibration
goodvibration

Reputation: 6206

Display values in fixed-format with matplotlib

There are several answers for this question on Stack Overflow, none of them seems to work.

Here is my plotting-code:

import matplotlib.pyplot as plt

arr = []

for n in range(3,13):
    for i in range(0,1000):
        val = 50000000 * float(i) / 10**n
        if val not in arr:
            arr.append(val)

arr.sort()

plt.plot(arr)
plt.grid(True)
plt.show()

I tried adding this line after the plt.plot(arr) line:

plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)

No luck with that.

How can I achieve this?

Upvotes: 0

Views: 387

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339220

What you see in the plot is not actually an offset, but a factor. This factor is used if scientific notation is enabled for the axis.

You may turn scientific notation off on the axis,

plt.gca().get_yaxis().get_major_formatter().set_scientific(False)

or use the more comprehensive .ticklabel_format method,

plt.gca().ticklabel_format(axis="y", style="plain")

Upvotes: 1

WillMonge
WillMonge

Reputation: 1035

This always bugs me quite a bit, because not all the answers work depending on how you are defining your plot.

For you case the following works (I simply imported and created a ScalarFormatter) and set it to your axis on the get_yaxis() line

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter 

# Create a tick formatter
non_sc_formatter = ScalarFormatter(useOffset=False)
non_sc_formatter.set_scientific(False)


arr = []

for n in range(3,13):
    for i in range(0,1000):
        val = 50000000 * float(i) / 10**n
        if val not in arr:
            arr.append(val)

arr.sort()

plt.plot(arr)
plt.gca().get_yaxis().set_major_formatter(non_sc_formatter)  # use the tick formatter
plt.grid(True)
plt.show()

Upvotes: 1

Related Questions