Adjust Text Positions in Matplotlib Plots
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
- breaking Version 1.0.0 introduced a 'new engine' with significant breaking API changes. Code written for versions prior to 1.0.0 may require updates to function correctly.
- gotcha It is crucial to call `adjust_text` as the very last step in your plotting code, after all other plot elements (especially those that might change axis limits) have been set. Failure to do so can lead to nonsensical or suboptimal text placement.
- gotcha The `v1.2.0` release provided specific compatibility for NumPy 2.0. Older versions of `adjustText` may encounter issues when used with NumPy 2.0 due to changes in NumPy's API and data type handling.
- gotcha Version 1.3.0 introduced experimental logic to prevent arrow crossings. While intended to improve plots, this new feature might, in some complex scenarios, introduce unexpected behavior or performance implications.
Install
-
pip install adjustText
Imports
- adjust_text
from adjustText import adjust_text
Quickstart
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()