Adjust Text Positions in Matplotlib Plots

1.3.0 · active · verified Sun Apr 12

adjustText is a Python library that iteratively adjusts the position of text labels in Matplotlib plots to minimize overlaps with other labels, data points, and plot boundaries. It is currently at version 1.3.0 and has a regular release cadence, often addressing compatibility and performance improvements. The approach is inspired by the `ggrepel` package for R/ggplot2.

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a scatter plot with overlapping text labels and then use `adjust_text` to automatically reposition them. Arrows are optionally added to connect the adjusted labels to their original data points.

import matplotlib.pyplot as plt
import numpy as np
from adjustText import adjust_text

# Generate some random data
np.random.seed(0)
x, y = np.random.random((2, 30))

# Create a matplotlib plot
fig, ax = plt.subplots()
ax.plot(x, y, 'o', markersize=5)

# Create text labels for each point
texts = []
for i, (xi, yi) in enumerate(zip(x, y)):
    texts.append(ax.text(xi, yi, f'Text{i}', ha='center', va='center'))

# Adjust text positions to minimize overlaps
adjust_text(texts, 
            arrowprops=dict(arrowstyle='-', color='gray', lw=0.5))

# Show the plot
plt.title('Adjusted Text Labels')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

view raw JSON →