Reputation: 369
I'd like to do some plots by matplotlib, but there is a problem that some of my tick labels are too long. I wonder if I can make long tick labels show in multi-lines.
Here is some code:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random(4)
idx = np.arange(4)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim(-0.5, 4-0.5)
ax.set_yticks(b)
ax.tick_params(length=0)
ax.barh(idx, data, zorder=2,
tick_label=["qwertyuioplkjhgfdsa+1s",
"abc","asd","qwerty"])
ax.grid(axis='x')
plt.show()
So here is the plot I got.
As you can see, the bottom ytick label is too long, and I want to set each line 10 letters at most, so I hope that tick label could be shown in
qwertyuiop
lkjhgfdsa+
1s
or somewhat not so long in one line.
Any help would be appreciated!
Upvotes: 6
Views: 9159
Reputation: 339580
You can use the textwrap
module of python. E.g. to wrap at 10 characters:
import textwrap
f = lambda x: textwrap.fill(x.get_text(), 10)
ax.set_yticklabels(map(f, ax.get_yticklabels()))
Upvotes: 5
Reputation: 19885
You can modify the tick labels right before showing your plot to have a newline every max_chars
characters:
max_chars = 10
new_labels = ['\n'.join(label._text[i:i + max_chars ]
for i in range(0, len(label._text), max_chars ))
for label in ax.get_yticklabels()]
ax.set_yticklabels(new_labels)
Upvotes: 2
Reputation: 199
try adding \n to it
ax.barh(idx, data, zorder=2,
tick_label=["qwertyuiop \n lkjhgfdsa+ \n 1s",
"abc","asd","qwerty"])
Upvotes: 2