Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing tick label line spacing in matplotlib

I have a quite cluttered plot with y-ticklabels that need to be very long. I've resorted into wrapping them into multiline text with textwrap. However that makes the labels overlap (or at least come too close), between categories.

I can't solve it by spacing the ticks, making the graph larger, changing font or making the text smaller. (I've already pushed these limits)

As I see it, I could resolve and make it work if I could adjust the line spacing/height to be less than what the font requests.

So imagine for simplicity's sake the following tick-label desperately needs shorter line distance between lines/line height:

from matplotlib import pyplot as plt
plt.barh(0.75, 10, height=0.5)
plt.ylim(0, 2)
plt.yticks([1], ["A very long label\nbroken into 2 line"])
plt.subplots_adjust(left=0.3)
plt.show()

I've checked plt.tick_params() the rcParams without finding any obvious solution. I'm using latex to format the text, but trying to use \hspace(0.5em} in the tick label string seemed not to work/only make things worse.

Any suggestion as to how the line spacing can be decreased would be much appreciated.

like image 653
deinonychusaur Avatar asked Nov 10 '22 04:11

deinonychusaur


1 Answers

You can use the linespacing keyword in your plt.yticks line. For example:

plt.yticks([1], ["A very long label\nbroken into 2 line"],linespacing=0.5)

You can play with the exact value of linespacing to fit your needs. Hope that helps.

Here's the original output of your code: default line spacing

And here it is with a linespacing of 0.5: enter image description here

like image 194
tmdavison Avatar answered Nov 14 '22 23:11

tmdavison