How to Set Axis Scale to Logarithmic in Matplotlib
To set an axis scale to logarithmic in Matplotlib, use the
set_xscale('log') or set_yscale('log') methods on the axis object. For example, ax.set_xscale('log') changes the x-axis to a log scale.Syntax
Use ax.set_xscale('log') to set the x-axis to logarithmic scale and ax.set_yscale('log') for the y-axis. Here, ax is the axis object from Matplotlib's plt.subplots(). The string 'log' specifies the logarithmic scale.
python
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_xscale('log') # Set x-axis to log scale ax.set_yscale('log') # Set y-axis to log scale
Example
This example shows how to plot data with a logarithmic x-axis and y-axis using Matplotlib. It demonstrates how the axis scales change the appearance of the plot.
python
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0.1, 10, 100) y = np.exp(x) fig, ax = plt.subplots() ax.plot(x, y) ax.set_xscale('log') ax.set_yscale('log') ax.set_title('Plot with Logarithmic X and Y Axis') ax.set_xlabel('Log X-axis') ax.set_ylabel('Log Y-axis') plt.show()
Output
A plot window showing a curve with both x-axis and y-axis scaled logarithmically.
Common Pitfalls
- Trying to set log scale on data containing zero or negative values causes errors because log scale requires positive values only.
- Forgetting to call
set_xscaleorset_yscaleon the correct axis object. - Using
plt.xscale('log')orplt.yscale('log')is also valid but less flexible when working with multiple subplots.
python
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 10, 100) # Contains negative values y = np.exp(x) fig, ax = plt.subplots() ax.plot(x, y) # This will raise an error because x has negative values # ax.set_xscale('log') # Wrong # Correct approach: filter positive values only x_pos = x[x > 0] y_pos = y[x > 0] ax.clear() ax.plot(x_pos, y_pos) ax.set_xscale('log') ax.set_yscale('log') plt.show()
Output
A plot window showing the curve with log-scaled axes after filtering out negative x values.
Quick Reference
| Method | Description | Example |
|---|---|---|
| set_xscale('log') | Set x-axis to logarithmic scale | ax.set_xscale('log') |
| set_yscale('log') | Set y-axis to logarithmic scale | ax.set_yscale('log') |
| plt.xscale('log') | Set current plot's x-axis to log scale | plt.xscale('log') |
| plt.yscale('log') | Set current plot's y-axis to log scale | plt.yscale('log') |
Key Takeaways
Use ax.set_xscale('log') or ax.set_yscale('log') to set logarithmic scales on axes.
Log scale requires all data values on that axis to be positive and non-zero.
Filtering out zero or negative values prevents errors when using log scale.
Using axis objects (ax) is preferred for plots with multiple subplots.
plt.xscale('log') and plt.yscale('log') work for simple single plots.