代码之家  ›  专栏  ›  技术社区  ›  Gonzalo

减少matplotlib图中的xticklabels区域

  •  -2
  • Gonzalo  · 技术社区  · 7 年前

    我的x轴标签(图下方的标签)正在从整个图形中窃取宝贵的空间。我试图通过更改文本旋转来减小其大小,但这没有多大帮助,因为文本标签很长。

    有没有更好的方法来减少xticklabel区域占用的空间?例如,我可以在条内显示此文本吗?谢谢你的支持。

    import matplotlib.pyplot as plt
    import matplotlib
    matplotlib.rcParams['font.sans-serif'] = "Century Gothic"
    matplotlib.rcParams['font.family'] = "Century Gothic"
    
    ax = df1.plot.bar(x = '', y = ['Events Today', 'Avg. Events Last 30 Days'], rot = 25, width=0.8 , linewidth=1, color=['midnightblue','darkorange'])
    
    for item in ([ax.xaxis.label, ax.yaxis.label] +
             ax.get_xticklabels() + ax.get_yticklabels()):
        item.set_fontsize(15)
    
    ax.legend(fontsize = 'x-large', loc='best')
    plt.tight_layout()
    ax.yaxis.grid(True, which='major', linestyle='-', linewidth=0.15)
    ax.set_facecolor('#f2f2f2')
    plt.show()
    

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   joelostblom    7 年前

    如果你坚持使用长名称和特定字体大小,我建议用水平条形图代替。我通常更喜欢标签较长的水平图,因为不旋转的文本更容易阅读(这也可能使字体大小进一步减小一步),添加换行符也会有所帮助。

    下面是一个带有笨拙标签的图形示例:

    import pandas as pd
    import seaborn as sns # to get example data easily
    
    iris = sns.load_dataset('iris')
    means = iris.groupby('species').mean()
    my_long_labels = ['looooooong_versicolor', 'looooooooog_setosa', 'looooooooong_virginica']
    # Note the simpler approach of setting fontsize compared to your question
    ax = means.plot(kind='bar', y=['sepal_length', 'sepal_width'], fontsize=15, rot=25)
    ax.set_xlabel('')
    ax.set_xticklabels(my_long_labels)
    

    enter image description here

    我将其更改为水平条形图:

    ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15)
    ax.set_ylabel('')
    ax.set_yticklabels(my_long_labels)
    

    enter image description here

    ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15, rot=0)
    ax.set_ylabel('')
    ax.set_yticklabels([label.replace('_', '\n') for label in my_long_labels])
    

    enter image description here

    这也适用于垂直条:

    ax = means.plot(kind='bar', y=['sepal_length', 'sepal_width'], fontsize=15, rot=0)
    ax.set_xlabel('')
    ax.set_xticklabels([label.replace('_', '\n') for label in my_long_labels])
    

    enter image description here

    最后,你也可以把文本放在条内,但这很难阅读。

    ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15)
    ax.set_ylabel('')
    ax.set_yticklabels(my_long_labels, x=0.03, ha='left', va='bottom')
    

    enter image description here