Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 846
user809167 Avatar asked Jun 21 '11 19:06

user809167


People also ask

How do I avoid scientific notation in MatPlotLib?

MatPlotLib with Python To prevent scientific notation, we must pass style='plain' in the ticklabel_format method.

How do you change the log scale in MatPlotLib?

pyplot library can be used to change the y-axis or x-axis scale to logarithmic respectively. The method yscale() or xscale() takes a single value as a parameter which is the type of conversion of the scale, to convert axes to logarithmic scale we pass the “log” keyword or the matplotlib.

How do I scale axis in MatPlotLib?

Import matplotlib. To set x-axis scale to log, use xscale() function and pass log to it. To plot the graph, use plot() function. To set the limits of the x-axis, use xlim() function and pass max and min value to it. To set the limits of the y-axis, use ylim() function and pass top and bottom value to it.

How do I change the Y scale in Python?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.


2 Answers

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.

like image 161
DSM Avatar answered Sep 29 '22 02:09

DSM


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()
like image 23
Joe Cat Avatar answered Sep 29 '22 03:09

Joe Cat