如何在matplotlib中将x轴标签显示为多行?

15

我试图让非常长的x轴标签变成多行,就像右图中圈出来的那样:

示例图像

我目前正在使用的代码:

ax = cluster3.plot(x='Neighborhood',y=['Population'],kind='bar',alpha=0.75,title='Population of Each Neighborhood',figsize=(15, 10))
ax.set_ylabel('Population')

cluster3是一个带有Neighborhood列的数据框

3个回答

12

请查看这张图片:For wrapping

或者

df['cluster3'] = ['\n'.join(wrap(x, 12)) for x in  df['cluster3'])

应用此方法到你的标签列中,将标签换行。


此外,您可能想要使用 textwrap.fill(),它(引用文档)""\n".join(wrap(text, ...))的简写。" - Skippy le Grand Gourou
1
@Strange 请不要发布代码图片。这是不好的做法,防止复制和粘贴,并浪费存储空间。您可以考虑将代码编写为文本以改善您的答案(当然要保留直方图图片)。 - mranvick

1

在你的标签和你想要换行的位置添加"\n"来插入换行。

如果你想每隔x个字符就自动换行,可以使用以下方法:

def insert_linebreak(string, lengLabel=48):
    return '\n'.join(string[i:i+lengLabel] for i in xrange(0, len(string), every))

标签来自数据框(cluster3)。您能建议一种方法将“\n”添加到标签中吗? - chronos203

0
对于任何较长的标签,可以在想要换行的位置放置\n字符。例如,"All creatures from out of space" 可以变成 "All creatures\nfrom out of space"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接