Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping long y labels in matplotlib tight layout using setp

I've been trying to wrap text for long labels in my code. I tried the textwrap method suggested earlier here, but my code defines yticklabels through an array imported from a csv using the pyplot.setp() method. I'm using tight_layout() for the formatting otherwise.

So the question is - is there a way to wrap the really long y labels to newlines easily?

Here is some sample code that I'd like a fix for:

import numpy as np import matplotlib.pyplot as plt  labels=('Really really really really really really long label 1', 'Really really really really really really long label 2', 'Really really really really really really long label 3') values=(30,50,40)  fig = plt.figure() ax=fig.add_subplot(111)  plt.ylim((0,40)) for i in np.arange(3):     plt.barh(15*i, values[i])  plt.yticks(15*np.arange(3)) plt.setp(ax.set_yticklabels(labels))  plt.tight_layout() plt.show() 

This plots something like this enter image description here I'd like the labels to go to newlines after a fixed width. Any ideas?

like image 687
chinmayn Avatar asked Apr 01 '13 09:04

chinmayn


People also ask

How do you wrap Xlabel in Python?

If you want to wrap the labels manually you can insert a '\n' into the label name, which will break the label into two lines at the point you have the '\n'. You can see an example of this here. There also appears to be an autowrap function now that seems to do the trick nicely.


2 Answers

I have tried using textwrap on the labels and it works for me.

from textwrap import wrap labels=['Really really really really really really long label 1',         'Really really really really really really long label 2',         'Really really really really really really long label 3'] labels = [ '\n'.join(wrap(l, 20)) for l in labels ] 

Inserting this in your code gives us:

Wrapped labels

like image 141
daedalus Avatar answered Sep 18 '22 19:09

daedalus


If you are looking for a fast way to wrap your labels dynamically, you can simply replace ' ' by '\n' like this :

wrapped_labels = [ label.replace(' ', '\n') for label in labels ] 
like image 40
boblatouffe Avatar answered Sep 21 '22 19:09

boblatouffe