简体   繁体   English

如何自动调整 matplotlib plot 的大小以适合 x 轴标签

[英]How to automatically size a matplotlib plot to fit the x axis labels

The data plots OK, but the rotated labels on the x axis are clipped.数据绘制正常,但 x 轴上的旋转标签被剪裁。 How do I open the plot such that everything fits?如何打开 plot 以使一切都适合?

def plot(data):
    import matplotlib.pyplot as plt
    # Uh oh. Our data is not what this logic expects. We need to break it into 2 lists
    
    plt.style.use('ggplot')

    breeds = [x[0] for x in data]
    totals = [x[1] for x in data]

    # 
    x_pos = [i for i, _ in enumerate(data)]   # Figure out where the bars will go

    plt.bar(x_pos, totals, color='green')
    plt.xlabel("Breed")
    plt.ylabel("Total Cows")
    plt.title("Total Cows by Breed")
    
    # We need to rotate the x axis labels to vertical because they are too long and they overlap
    plt.xticks(rotation = 90)
    plt.xticks(x_pos, breeds)  # x_pos matches one-to-one with breeds
    
    plt.show()
    
if __name__ == '__main__':
    data = [["brown",100],["White",200], ["Zebra",4000], ["Unknown", 4500]]
    plot(data)

在此处输入图像描述

you can do use tight layout:你可以使用紧凑的布局:

    ...
    plt.tight_layout()
    plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM