如何处理大标签(文本在 python 条形图中被裁剪)

How to handle large labels (text got cropped in python barchart )

我有这个数据

y1= [2232424, 2324353, 0, 8433232, 21421521, 2164216, 2761731,  752164215]
y2=[0, 32, 253, 6271, 263, 5535142, 1513153, 92512152]

我绘制了条形图 .. 但我将条形图的标签旋转了 30 度,因为标签很大。但即使在旋转 30 度后,文本也会被裁剪,您可以在下图中看到。如何解决这个问题

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    plt.rcParams.update({'font.size': 16})
    from matplotlib.pyplot import figure
    figure(figsize=(8, 6), dpi=80)
    
    x = np.array([0,1,2,3,4,5,6,7])
    L = ['AAAAAA', 'BBBB', 'CCCCCC','DDDDDD', 'EEEEE', 'FFFFFFFFF', 'FGGGGG','HHHHHHHHHH']  
    y1= [2232424, 2324353, 0, 8433232, 21421521, 2164216, 2761731,  752164215]
    y2=[0, 32, 253, 6271, 263, 5535142, 1513153, 92512152]
    
    width = 0.40
    plt.bar(x - width/2, y1, width)
    plt.bar(x + width/2, y2, width)
    
    plt.legend(['one', 'two'], loc='upper right')
    plt.xticks(x, L, rotation=30, horizontalalignment='left')
    plt.show()

我已经回答了你之前关于转换的问题。

这时候你需要了解布局设置。

matplotlib 提供强大的自动设置布局功能。

使用紧凑的布局(https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html)

# recttuple (left, bottom, right, top), default: (0, 0, 1, 1)
plt.tight_layout()

另外如果觉得matplotlib不好用,用seaborn是更好的选择

import seaborn as sns
import matplotlib.pyplot as plt

data = pd.DataFrame(dict(
    y1     = [2232424, 2324353, 0, 8433232, 21421521, 2164216, 2761731,  752164215],
    y2     = [0, 32, 253, 6271, 263, 5535142, 1513153, 92512152],
    labels = ['AAAAAA', 'BBBB', 'CCCCCC','DDDDDD', 'EEEEE', 'FFFFFFFFF', 'FGGGGG','HHHHHHHHHH']
)).melt(id_vars=['labels'], value_vars=['y1', 'y2'])

plt.figure(figsize=(8, 6), dpi=80)

ax = sns.barplot(x='labels', y='value', hue='variable', data=data)

plt.xticks(rotation=30, horizontalalignment='right')
plt.tight_layout()
plt.show()