【问题标题】:How to get x axis labels in multiple line in matplotlib?如何在matplotlib的多行中获取x轴标签?
【发布时间】:2020-04-15 09:06:04
【问题描述】:

我正在尝试将很长的 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 列的数据框

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    检查此图像:

    或者

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

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

    【讨论】:

    • 另外,您可能想使用textwrap.fill(),它(引用the documentation)“"\n".join(wrap(text, ...))的简写”。
    【解决方案2】:

    通过将"\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”添加到标签的方法吗?
    猜你喜欢
    • 2012-03-13
    • 2020-11-30
    • 1970-01-01
    • 2012-11-11
    • 2020-09-14
    • 2019-01-24
    • 2017-08-24
    • 2013-03-24
    • 1970-01-01
    相关资源
    最近更新 更多