The content of this answer has been merged into mpl master at https://github.com/matplotlib/matplotlib/pull/4342 and will be in the next release of the function.
Wow ... This is a difficult problem ... (And it provides many limitations in matplotlib text rendering ...)
This should (imo) be what matplotlib has inline, but it is not. There were several on the mailing list, but there was no solution that could be found for automatic text portability.
So, firstly, there is no way to determine the size (in pixels) of the displayed text string before it is drawn in matplotlib. This is not a big problem, since we can just draw it, get the size, and then redraw the wrapped text. (It's expensive, but not too much)
The next problem is that the characters do not have a fixed width in pixels, so wrapping a text string by a given number of characters will not necessarily reflect the specified width when rendering. However, this is not a big problem.
In addition, we cannot just do it once ... Otherwise, it will be correctly packed when it is drawn for the first time (for example, on the screen), but not in the case of repeated drawing (when resizing or saved as an image with other DPI than the screen). This is not a big problem, as we can just hook the callback function to the matplotlib draw event.
In any case, this solution is imperfect, but it should work in most situations. I'm not trying to take into account tex-rendering strings, any stretched fonts or fonts with an unusual aspect ratio. However, now it should correctly handle rotated text.
However, he should try to automatically wrap any text objects in several subheadings depending on what numbers you connect with the on_draw to ... In many cases, this will be imperfect, but it does a decent job.
import matplotlib.pyplot as plt def main(): fig = plt.figure() plt.axis([0, 10, 0, 10]) t = "This is a really long string that I'd rather have wrapped so that it"\ " doesn't go outside of the figure, but if it long enough it will go"\ " off the top or bottom!" plt.text(4, 1, t, ha='left', rotation=15) plt.text(5, 3.5, t, ha='right', rotation=-15) plt.text(5, 10, t, fontsize=18, ha='center', va='top') plt.text(3, 0, t, family='serif', style='italic', ha='right') plt.title("This is a really long title that I want to have wrapped so it"\ " does not go outside the figure boundaries", ha='center')
