0

I have a plot with a long text string that was inserted (string not determined by me, so I can't shorten it):

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]]
z = [1, 2, 3]

lc = LineCollection(lines, array=z, cmap="coolwarm", linewidth = 8)

fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()

fig.colorbar(lc)
ax.text(2,3,'some very long text that will go outside of the plot boundaries')
plt.savefig('tmp.png')

which generates the following:

enter image description here

as you can see, the long text goes outside of the plot area.

matplotlib text only in plot area is similar, but I cannot clip the text.

I have also tried subplots.adjust() (Increasing the space for x axis labels in Matplotlib) but that generates something even worse:

enter image description here

I've also thought of using some other way than subplots, but subplots seem to be standard practice: https://matplotlib.org/stable/gallery/shapes_and_collections/line_collection.html

How can I extend the plot area to the maximum extent of the text?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
con
  • 5,767
  • 8
  • 33
  • 62
  • `ax.set_xlim(0, 5)` (pick a number), or move the start location, or wrap the text – Trenton McKinney Aug 30 '23 at 19:57
  • but how can I know how to set `5`? I'm making hundreds of plots like this, and the number will almost certainly be different from plot to plot – con Aug 30 '23 at 19:58
  • [Text box with line wrapping in matplotlib?](https://stackoverflow.com/q/4018860/7758804), [How to insert non overlapping text](https://stackoverflow.com/q/13437327/7758804), [Set the limits for text wrapping](https://stackoverflow.com/q/43087087/7758804) – Trenton McKinney Aug 30 '23 at 20:03
  • [How to put text outside of plots](https://stackoverflow.com/a/42439154/7758804): _It's probably best to define the position in figure coordinates instead of data coordinates_ – Trenton McKinney Aug 30 '23 at 20:11
  • You can also set a new line in the text. `ax.text(2, 2.8,'some very long text that will go\noutside of the plot boundaries')` – Trenton McKinney Aug 30 '23 at 20:18

0 Answers0