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

dgenwo3n  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(95)

数据绘图正常,但x轴上的旋转标签被剪切。如何打开绘图以使所有内容都适合?

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)

8fq7wneg

8fq7wneg1#

你可以使用紧凑的布局:

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

相关问题