Categories
Python Answers

How to fix Python Matplotlib overlapping annotations or text?

Spread the love

Sometimes, we want to fix Python Matplotlib overlapping annotations or text.

In this article, we’ll look at how to fix Python Matplotlib overlapping annotations or text.

How to fix Python Matplotlib overlapping annotations or text?

To fix Python Matplotlib overlapping annotations or text, we can use the adjustText library.

To install it, we run

pip install adjustText

Then we use it by writing

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

together = [(0, 1.0, 0.4), (25, 1.013, 0.41), (50, 1.016, 0.41), (75, 1.10434, 0.42), (100, 1.161044, 0.44), (125, 1.16856, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.401399, 0.45)]

together.sort()

text = [x for (x,y,z) in together]
eucs = [y for (x,y,z) in together]
covers = [z for (x,y,z) in together]

p1 = plt.plot(eucs,covers,color="black", alpha=0.5)
texts = []
for x, y, s in zip(eucs, covers, text):
    texts.append(plt.text(x, y, s))

plt.xlabel("x")
plt.ylabel("y")
plt.title("Test plot")
adjust_text(texts, only_move={'points':'y', 'texts':'y'}, arrowprops=dict(arrowstyle="->", color='r', lw=0.5))
plt.show()

to create the together list with the points we wan tto plot.

And then we create lists with the x, y and z axis values from the together list.

Next, we call plot to plot the values.

And then we append the text with the for loop.

And then we call adjust_text to move the texts so that they won’t over.

We specify that we move the points and texts in the y direction.

Conclusion

To fix Python Matplotlib overlapping annotations or text, we can use the adjustText library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *