MoChen
MoChen

Reputation: 317

Creating Pie Subplots of Circular Type in Python

I am trying to create a pie subplot in a plot using a DF. But all my pie charts are not actual circular but the first two are coming as ellipse.Please guide me how to make all the subplots of same size and circular. Codes that I am using is given below

fig = plt.figure()
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)

ax1 = test1_pie.plot(kind='pie',y=test1,ax =ax1)
plt.axis('equal')

ax2 = test2_pie.plot(kind='pie',y=test2,ax=ax2)
plt.axis('equal')

ax3 = test3_pie.plot(kind='pie',y=test3,ax=ax3)
plt.axis('equal')

Upvotes: 3

Views: 4543

Answers (1)

Joe Kington
Joe Kington

Reputation: 284582

It's a bad idea to mix state-machine pyplot calls and normal axes method calls. This is a classic example of why.

plt.<whatever> will refer to the last axes created in this case. You're only calling axis('equal') on the last axes object.

It's best to stick to the normal axes-method api instead.

For example:

fig = plt.figure()
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)

ax1 = test1_pie.plot(kind='pie', y=test1, ax=ax1)
ax1.axis('equal')

ax2 = test2_pie.plot(kind='pie', y=test2, ax=ax2)
ax2.axis('equal')

ax3 = test3_pie.plot(kind='pie', y=test3, ax=ax3)
ax3.axis('equal')

As a stand-alone example:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=3)

for ax in axes:
    x = np.random.random(np.random.randint(3, 6))
    ax.pie(x)
    ax.axis('equal')

plt.show()

enter image description here

Upvotes: 1

Related Questions