5

I'm trying to plot a graph with long x label strings. This post describes a similar problem (how to autowrap y-axis labels with tight_layout) but doesn't work for me because tight_layout changes the scale. This other post describes an approach that does NOT achieve automatic wrapping of axis labels - the package textwrap requires one to specify the number of characters to wrap around.

My code:

import matplotlib.pyplot as plt
plt.figure()
plt.bar([0,1,2,3],[0,1,4,9])        
labels = ['superdupersuperduperlonglabel0','superdupersuperduperlonglabel1',
    'superdupersuperduperlonglabel2','superdupersuperduperlonglabel3']
plt.xticks([0,1,2,3],labels, wrap = True)
plt.show()

This is the resulting plot, with x labels overlapping: This is the resulting plot, with x labels overlapping.

According to matplotlib documentation:

Text properties can be used to control the appearance of the labels.

But wrap = True doesn't seem to wrap the x-labels properly. Any suggestion?

xyzjayne
  • 1,331
  • 9
  • 25
  • 2
    `wrap=True` wraps at the figure boundaries, else it wouldn't know where to wrap. The suggested solution using `'\n'.join(wrap(l, 12))` [works fine for me](https://i.stack.imgur.com/3G7PZ.png), no need for tight_layout at all. You may want to solve the problem of the dead interpreter instead of finding workarounds for the one package that would do the job. – ImportanceOfBeingErnest Jun 08 '18 at 21:21
  • 1
    @ImportanceOfBeingErnest The solution is not satisfactory because you need to manually specify the number of characters to wrap at, which could change with respect to many factors such as plot size, font size, number of x-labels, etc. It's clear in the title that I'm looking for a solution that would "autowrap". – xyzjayne Jul 18 '18 at 19:57

0 Answers0