Matplotlib / Matlab log axis plots

In Python Matplotlib or Matlab, making a plot with log-scaled (instead of default linear-scaled) axes can use the functions like “loglog()”, “semilogx()”, or “semilogy()”. Here we show the more general object-oriented syntax for each of a 2-D line “plot()” and 2-D pseudocolor “pcolor()” and then set the axes scale properties.

We arbitrarily use log abscissa scale and linear ordinate scale, but the same syntax applies to other combinations.

Python

2-D line plot:

import numpy as np
from matplotlib.pyplot import figure, show

x = np.logspace(0, 10, 100)
y = np.log(x)**2

fg = figure()
ax = fg.gca()

ax.plot(x, y)
ax.set_xscale('log')

ax.set_xlabel('x')
ax.set_ylabel('y')

show()

pseudocolor pcolormesh(): observe the stretching of the ticks along the y-axis. In some cases it’s helpful to set the axis limits manually to avoid whitespace past the last data point.

import numpy as np
from matplotlib.pyplot import figure, show

d = np.random.rand(10, 10)
x = np.linspace(1, 10, d.shape[0])
y = np.logspace(0, 1, d.shape[1])

fg = figure()
ax = fg.gca()

ax.pcolormesh(x, y, d)
ax.set_yscale('log')
ax.set_ylim(y[0], y[-1])

ax.set_xlabel('x')
ax.set_ylabel('y')

show()

Matlab

2-D line plot:

x = logspace(0, 10, 100);
y = log(x).^2;

fg = figure();
ax = axes(fg);

plot(ax, x, y);
ax.XScale = 'log';

xlabel(ax, 'x');
ylabel(ax, 'y');

pseudocolor pcolor(): observe the stretching of the ticks along the y-axis. In some cases it’s helpful to set the axis limits manually to avoid whitespace past the last data point.

d = rand(10, 10);
x = linspace(1, 10, size(d, 1));
y = logspace(0, 1, size(d, 2));

fg = figure();
ax = axes(fg);

pcolor(ax, x, y, d);
ax.YScale = 'log';

xlabel(ax, 'x');
ylabel(ax, 'y');