Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to show minor tick labels on a log-scale with Matplotlib?
In Matplotlib, displaying minor tick labels on a log-scale plot requires special formatting since log scales typically only show major ticks by default. We can achieve this by using the tick_params() method and FormatStrFormatter to control minor tick appearance.
Basic Log-Scale Plot with Minor Ticks
Here's how to create a log-scale plot and display minor tick labels ?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points
x = np.linspace(-2, 2, 10)
y = np.exp(x)
# Plot the data
plt.plot(x, y)
# Get current axis and set log scale
ax = plt.gca()
ax.set_yscale('log')
# Enable minor tick labels and set formatter
plt.tick_params(axis='y', which='minor')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f"))
plt.show()
Step-by-Step Process
The key steps to show minor tick labels on a log-scale are ?
- Set the y-axis scale to logarithmic using
set_yscale('log') - Enable minor ticks with
tick_params(axis='y', which='minor') - Format minor tick labels using
set_minor_formatter() - Use
FormatStrFormatterto specify the number format
Customizing Minor Tick Appearance
You can further customize the appearance of minor ticks ?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
# Create sample data
x = np.linspace(1, 100, 50)
y = x**2
plt.figure(figsize=(8, 6))
plt.plot(x, y, 'b-', linewidth=2)
ax = plt.gca()
ax.set_yscale('log')
# Customize minor tick appearance
plt.tick_params(axis='y', which='minor', labelsize=8, color='gray')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.0f"))
plt.xlabel('X values')
plt.ylabel('Y values (log scale)')
plt.title('Log Scale with Custom Minor Ticks')
plt.grid(True, which='both', alpha=0.3)
plt.show()
Key Parameters
| Parameter | Purpose | Example Values |
|---|---|---|
which='minor' |
Target minor ticks | 'major', 'minor', 'both' |
FormatStrFormatter |
Format tick labels | "%.1f", "%.0f", "%.2e" |
labelsize |
Control label size | 8, 10, 12 |
Conclusion
To show minor tick labels on log-scale plots, use tick_params(which='minor') to enable them and set_minor_formatter() to control their appearance. This provides better readability for logarithmic data visualization.
Advertisements
