Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show minor tick labels on log-scale with Matplotlib

Does anyone know how to show the labels of the minor ticks on a logarithmic scale with Python/Matplotlib?

like image 347
Tomas Avatar asked Jun 17 '15 09:06

Tomas


People also ask

How do I show a minor tick in Matplotlib?

To locate minor ticks, use set_minor_locator() method. To show the minor ticks, use grid(which='minor'). To display the figure, use show() method.

How do I get rid of minor ticks in Matplotlib?

Matplotlib removes both labels and ticks by using xticks([]) and yticks([]) By using the method xticks() and yticks() you can disable the ticks and tick labels from both the x-axis and y-axis.


2 Answers

You can use plt.tick_params(axis='y', which='minor') to set the minor ticks on and format them with the matplotlib.ticker FormatStrFormatter. For example,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
x = np.linspace(0,4,1000)
y = np.exp(x)
plt.plot(x, y)
ax = plt.gca()
ax.set_yscale('log')
plt.tick_params(axis='y', which='minor')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f"))
plt.show()

enter image description here

like image 88
xnx Avatar answered Oct 11 '22 12:10

xnx


One option is to use matplotlib.ticker.LogLocator

import numpy
import pylab
import matplotlib.pyplot
import matplotlib.ticker
## setup styles
from  matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Times-Roman']})
rc('text', usetex = True)
matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]

## make figure
figure, ax = matplotlib.pyplot.subplots(1, sharex = True, squeeze = True)
x = numpy.linspace(0.0, 20.0, 1000)
y = numpy.exp(x)
ax.plot(x, y)
ax.set_yscale('log')

## set y ticks
y_major = matplotlib.ticker.LogLocator(base = 10.0, numticks = 5)
ax.yaxis.set_major_locator(y_major)
y_minor = matplotlib.ticker.LogLocator(base = 10.0, subs = numpy.arange(1.0, 10.0) * 0.1, numticks = 10)
ax.yaxis.set_minor_locator(y_minor)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

## save figure
pylab.tight_layout()
pylab.savefig('./test.png', dpi = 200)

you would get

minor ticks

the only thing you need to manually adjust is the numticks input for both major and minor ticks, they both have to be a fraction of total possible number of major ticks.

like image 23
zyy Avatar answered Oct 11 '22 12:10

zyy