Adam Liu
Adam Liu

Reputation: 1346

Matplotlib subplots size not equal

I am using subplot to display some figures, however the labels are mixed with the last subplot, so the plots don't have equal size. and the previous 5 are not perfectly round circle.

Here's my code:

for i in range(6):
    plt.subplot(231 + i)
    plt.title("Department " + depts[i])
    labels = ['Male', 'Female']
    colors = ['#3498DB', '#E74C3C']
    sizes = [male_accept_rates[i] / (male_accept_rates[i] + female_accept_rates[i]),
             female_accept_rates[i] / (male_accept_rates[i] + female_accept_rates[i])]
    patches, texts = plt.pie(sizes, colors=colors, startangle=90)
plt.axis('equal')
plt.tight_layout()
plt.legend(labels, loc="best")
plt.show()

And here's the output: piecharts

can anyone give me some advise? Much appreciated.

Upvotes: 0

Views: 1154

Answers (1)

Douglas Dawson
Douglas Dawson

Reputation: 556

It appears plt.axis('equal') only applies to the last subplot. So your fix is to put that line of code in the loop.

So:

import numpy as np
import matplotlib.pyplot as plt

depts = 'abcdefg'
male_accept_rates =  np.array([ 2, 3, 2, 3, 4, 5], float)
female_accept_rates= np.array([ 3, 3, 4, 3, 2, 4], float)

for i in range(6):
    plt.subplot(231 + i)
    plt.title("Department " + depts[i])
    labels = ['Male', 'Female']
    colors = ['#3498DB', '#E74C3C']
    sizes = [male_accept_rates[i] / (male_accept_rates[i] + female_accept_rates[i]),
             female_accept_rates[i] / (male_accept_rates[i] + female_accept_rates[i])]
    patches, texts = plt.pie(sizes, colors=colors, startangle=90)
    plt.axis('equal')                                                                                          
plt.tight_layout()                                                                                             
plt.legend(labels, loc="best")                                                                                 
plt.show()

Produces this now: enter image description here

Upvotes: 1

Related Questions