Seaborn: Is There A Better Way To Wrap The Text In My Bar Plot?
Solution 1:
As @ImportanceOfBeingErnest pointed out, you can use the textwrap
module to do this, specifically useful would be textwrap.fill()
:
textwrap.fill(text[, width[, ...]])
Wraps the single paragraph in text so every line is at most
width
characters long, and returns a single string containing the wrapped paragraph.fill()
is shorthand for"\n".join(wrap(text, ...))
Although you will need to call this on each label separately with something like
ax.set_yticklabels([textwrap.fill(e, width) for e in data[y].head()])
Edit
Here is a more complete example to show the usage:
import textwrap
import matplotlib.pyplot as plt
import pandas as pd
df = {'Client Name': ['Some Name', 'Some long company name', 'Name',
'Company', 'Long Comany Name'],
'Col 1': [51235, 152, 12554, 12464, 12434]}
data = pd.DataFrame(df)
fig, ax = plt.subplots(1)
ax.set_yticklabels(data['Client Name'].head())
plt.show()
This will show the following
whereas
ax.set_yticklabels([textwrap.fill(e, 7) for e in data['Client Name'].head()])
plt.show()
will show something more like
Solution 2:
textwrap
seems easy to use, but it splits the sentence at a predetermined number of characters. Here is a function to insert a newline symbol (\n
) every n
words. You can then use out
as labels x- (or y-) axis tick marks. It might also be wise to avoid any unnecessary package dependencies.
Lst = ['You can never understand one language until you understand at least two.',
'Language is the blood of the soul into which thoughts run and out of which they grow.']
InsertNewlines = lambda lst, n=2: '\n'.join([' '.join(lst[i:i + n]) for i in range(0, len(lst), n)]) # n=words to keep togetherout = [InsertNewlines(s.split()) for s in Lst]
Output:
['You can\nnever understand\none language\nuntil you\nunderstand at\nleast two.',
'Language is\nthe blood\nof the\nsoul into\nwhich thoughts\nrun and\nout of\nwhich they\ngrow.']
Post a Comment for "Seaborn: Is There A Better Way To Wrap The Text In My Bar Plot?"