How can I get the length of a single unit on an axis in Matplotlib?

To get the length of a single unit on an axis in Matplotlib, you need to use the transData transform to convert data coordinates to display coordinates. This helps determine how many pixels represent one unit on each axis.

Understanding the Transform Method

The transData transform converts data coordinates to display (pixel) coordinates. By transforming unit vectors and comparing them to the origin, we can calculate the pixel length of a single unit on each axis.

Example

Here's how to calculate the length of a single unit on both axes ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.arange(0, 10, 0.005)
y = np.exp(-x / 2.) * np.sin(2 * np.pi * x)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)

# Calculate unit lengths using transform
xy = ax.transData.transform([(0, 1), (1, 0)]) - ax.transData.transform((0, 0))

print("Vertical length:", xy[0][1])
print("Horizontal length:", xy[1][0])

plt.show()

The output of the above code is ?

Vertical length: 269.5
Horizontal length: 581.25

How It Works

The calculation works by:

  • Transforming points (0, 1) and (1, 0) to display coordinates
  • Subtracting the transformed origin (0, 0) from both
  • The result gives the pixel distance for one unit on each axis

Alternative Method Using Axis Limits

You can also calculate unit length using axis limits and figure dimensions ?

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))

x = np.linspace(0, 10, 100)
y = np.sin(x)
ax.plot(x, y)

# Get axis limits
xlim = ax.get_xlim()
ylim = ax.get_ylim()

# Get figure size in pixels (assuming 100 dpi)
fig_width_px = fig.get_figwidth() * 100
fig_height_px = fig.get_figheight() * 100

# Calculate approximate unit lengths
x_unit_length = fig_width_px / (xlim[1] - xlim[0])
y_unit_length = fig_height_px / (ylim[1] - ylim[0])

print(f"X-axis unit length: {x_unit_length:.2f} pixels")
print(f"Y-axis unit length: {y_unit_length:.2f} pixels")

plt.show()
X-axis unit length: 80.00 pixels
Y-axis unit length: 300.00 pixels

Use Cases

Knowing unit lengths is useful for:

  • Creating annotations with consistent sizing
  • Positioning elements relative to data coordinates
  • Calculating aspect ratios for plots
  • Custom drawing operations that need pixel-perfect placement

Conclusion

Use transData.transform() for precise unit length calculations in Matplotlib. This method accounts for axis scaling, figure size, and subplot positioning to give accurate pixel measurements for data units.

Updated on: 2026-03-25T23:40:16+05:30

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements