如何在matplotlib中以多行获取x轴标签?

chr*_*203 6 python matplotlib python-3.x

我正在尝试将很长的 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')
Run Code Online (Sandbox Code Playgroud)

cluster3 是具有 Neighborhood 列的数据框

Str*_*nge 6

检查此图像: 包装用

或者

df['cluster3'] = ['\n'.join(wrap(x, 12)) for x in  df['cluster3'])
Run Code Online (Sandbox Code Playgroud)

将此应用于您的标签列以包装标签。


Axb*_*ert 1

"\n"通过添加到各自的标签和想要换行的位置来添加换行符

如果您想制定每 x 个字符添加换行符的规则,这对您有用:

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