0
0
Matplotlibdata~5 mins

Log scale and symlog scale in Matplotlib

Choose your learning style9 modes available
Introduction

Log scale helps us see data that changes a lot by shrinking big numbers and stretching small ones. Symlog scale lets us do this even if data has negative or zero values.

When your data covers many orders of magnitude, like population sizes or earthquake strengths.
When you want to compare small and large values clearly on the same graph.
When your data includes negative values but you still want a log-like scale.
When zero values appear in your data and you want to visualize them without errors.
Syntax
Matplotlib
ax.set_xscale('log')
ax.set_yscale('log')

ax.set_xscale('symlog', linthresh=1)
ax.set_yscale('symlog', linthresh=1)

Use 'log' for normal logarithmic scale (only positive values allowed).

Use 'symlog' for symmetric log scale that handles negative and zero values with a linear region around zero defined by linthresh.

Examples
This sets the y-axis to log scale to better show data that grows fast.
Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 10, 100, 1000])
ax.set_yscale('log')
plt.show()
This uses symlog scale on y-axis to handle negative and positive cubic values smoothly.
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10, 10, 400)
y = x**3

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_yscale('symlog', linthresh=100)
plt.show()
Sample Program

This program shows two plots: one with log scale only for positive y values, and one with symlog scale that handles negative y values smoothly.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Data with wide range and negative values
x = np.linspace(-100, 100, 500)
y = x**3

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6,8))

# Normal log scale (only positive values)
ax1.plot(x[x>0], y[x>0])
ax1.set_yscale('log')
ax1.set_title('Log scale (positive y only)')

# Symlog scale (handles negative and zero)
ax2.plot(x, y)
ax2.set_yscale('symlog', linthresh=100)
ax2.set_title('Symlog scale (handles negative values)')

plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Log scale cannot show zero or negative values; it will cause errors if used directly.

Symlog scale uses a linear region near zero to avoid issues with zero and negative values.

Adjust linthresh in symlog to control the size of the linear region around zero.

Summary

Log scale helps visualize data that changes exponentially but only works with positive values.

Symlog scale extends log scale to include negative and zero values by adding a linear zone near zero.

Use symlog when your data includes negative or zero values but you want log-like scaling.