user809167
user809167

Reputation: 241

Matplotlib - logarithmic scale, but require non-logarithmic labels

How can I stop the y-axis displaying a logarithmic notation label on the y-axis?

I'm happy with the logarithmic scale, but want to display the absolute values, e.g. [500, 1500, 4500, 11000, 110000] on the Y-axis. I don't want to explicitly label each tick as the labels may change in the future (I've tried out the different formatters but haven't successfully gotten them to work). Sample code below.

Thanks,

-collern2

import matplotlib.pyplot as plt
import numpy as np

a = np.array([500, 1500, 4500, 11000, 110000])
b = np.array([10, 20, 30, 40, 50])

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_yscale('log')

plt.plot(b, a)
plt.grid(True)
plt.show()

Upvotes: 24

Views: 15934

Answers (2)

DSM
DSM

Reputation: 353569

If I understand correctly,

ax.set_yscale('log')

any of

ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%d'))
ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, pos: str(int(round(x)))))

should work. '%d' will have problems if the tick labels locations wind up being at places like 4.99, but you get the idea.

Note that you may need to do the same with the minor formatter, set_minor_formatter, depending on the limits of the axes.

Upvotes: 33

Joe Cat
Joe Cat

Reputation: 207

Use ticker.FormatStrFormatter

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

a = np.array([500, 1500, 4500, 11000, 110000])
b = np.array([10, 20, 30, 40, 50])

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_yscale('symlog')

ax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%d"))

plt.plot(b, a)
plt.grid(True)

plt.show()

Upvotes: 3

Related Questions