zyy
zyy

Reputation: 1574

How can I control the number of tick labels for an axis in logarithm scale with matplotlib?

I am trying to make a figure with a few subplots, where the x axis for some of them were set to logarithm scale. However, the tick labels are getting crowded and I have no idea of how to reduce the number of tick labels.

I tried matplotlib.pyplot.locator_params(axis = 'x', nbins = 2) but it does not work for axises in logarithm scale, I also tried

x_tick_locations = matplotlib.ticker.LogLocator(numticks = 2)
ax.xaxis.set_major_locator(x_tick_locations)

but get no luck. I know I can always manipulate by hand, but there are many subplots and I prefer a automated way of doing this.

Is there a way to limit number of tick labels for an axis in logarithm scale?

Thanks in advance!

Upvotes: 0

Views: 235

Answers (1)

r-beginners
r-beginners

Reputation: 35115

I don't have much experience with this type of graph, but I've customized the information from the official website to A sample was created for setting the x-axis range with plt.xlim(). The setting information was based on SO answer.

import matplotlib.pyplot as plt
import numpy as np

# fig, ax = plt.subplots()
fig = plt.figure(figsize=(8,4),dpi=144)

dt = 0.01
t = np.arange(dt, 20.0, dt)

ax1 = plt.subplot(211)
ax1.semilogx(t, np.exp(-t / 5.0))
ax1.grid()

ax2 = plt.subplot(212, sharex=ax1)
ax2.loglog(t, 20 * np.exp(-t / 10.0), basex=10)
ax1.grid()

# Changing the x-axis range
plt.xlim([1, 10**2])

plt.show()

Graph before setting parameters:

enter image description here

Graph after setting parameters:

enter image description here

Upvotes: 2

Related Questions