Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyLab: Plotting axes to log scale, but labelling specific points on the axes

Basically, I'm doing scalability analysis, so I'm working with numbers like 2,4,8,16,32... etc and the only way graphs look rational is using a log scale.

But instead of the usual 10^1, 10^2, etc labelling, I want to have these datapoints (2,4,8...) indicated on the axes

Any ideas?

like image 606
Bolster Avatar asked Feb 24 '23 13:02

Bolster


1 Answers

There's more than one way to do it, depending on how flexible/fancy you want to be.

The simplest way is just to do something like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.exp2(np.arange(10))

plt.semilogy(x)
plt.yticks(x, x)

# Turn y-axis minor ticks off 
plt.gca().yaxis.set_minor_locator(mpl.ticker.NullLocator())

plt.show()

enter image description here

If you want to do it in a more flexible manner, then perhaps you might use something like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.exp2(np.arange(10))

fig = plt.figure()
ax = fig.add_subplot(111) 
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)

# This will place 1 minor tick halfway (in linear space) between major ticks
# (in general, use np.linspace(1, 2.0001, numticks-2))
ax.yaxis.get_minor_locator().subs([1.5])

ax.yaxis.get_major_formatter().base(2)

plt.show()

enter image description here

Or something like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.exp2(np.arange(10))

fig = plt.figure()
ax = fig.add_subplot(111) 
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)

ax.yaxis.get_minor_locator().subs([1.5])

# This is the only difference from the last snippet, uses "regular" numbers.
ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

plt.show()

enter image description here

like image 54
Joe Kington Avatar answered May 03 '23 18:05

Joe Kington