3

The data plots OK, but the rotated labels on the x axis are clipped. How do I open the plot such that everything fits?

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)

enter image description here

3
  • Save the figure as .svg and add bbox_inches='tight': plt.savefig(filename + ".svg", bbox_inches='tight') Commented Dec 17, 2021 at 14:53
  • @CLRW97 How do I get it to work when I call plt.show() ? Commented Dec 17, 2021 at 14:57
  • plt.tight_layout() Commented Dec 17, 2021 at 15:01

1 Answer 1

5

you can use tight layout :

    ...
    plt.tight_layout()
    plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.