Arrangement of pie charts using matplotlib subplot
10,584
A better method which I always use and is more intuitive, at-least for me, is to use subplot2grid
....
fig = plt.figure(figsize=(18,10), dpi=1600)
#this line will produce a figure which has 2 row
#and 4 columns
#(0, 0) specifies the left upper coordinate of your plot
ax1 = plt.subplot2grid((2,4),(0,0))
plt.pie(df_14,colors=("g","r"))
plt.title('EventLogs')
#next one
ax1 = plt.subplot2grid((2, 4), (0, 1))
plt.pie(df_24,colors=("g","r"))
plt.title('InstalledApp')
And you can go on like this, and when you want to switch the row just write the coordinate as (1, 0)... which is second row-first column.
An example with 2 rows and 2 cols -
fig = plt.figure(figsize=(18,10), dpi=1600)
#2 rows 2 columns
#first row, first column
ax1 = plt.subplot2grid((2,2),(0,0))
plt.pie(df.a,colors=("g","r"))
plt.title('EventLogs')
#first row sec column
ax1 = plt.subplot2grid((2,2), (0, 1))
plt.pie(df.a,colors=("g","r"))
plt.title('EventLog_2')
#Second row first column
ax1 = plt.subplot2grid((2,2), (1, 0))
plt.pie(df.a,colors=("g","r"))
plt.title('InstalledApp')
#second row second column
ax1 = plt.subplot2grid((2,2), (1, 1))
plt.pie(df.a,colors=("g","r"))
plt.title('InstalledApp_2')
Hope this helps!
Author by
user3447653
Updated on June 05, 2022Comments
-
user3447653 almost 2 years
I have 7 pi-charts (4 are listed below). I am trying to create a dashboard with 4 pie charts in first row and 3 pie charts in second row. Not sure where I am going wrong with the below code. Are there any other alternatives to achieve this? Any help would be appreciated.
from matplotlib import pyplot as PLT fig = PLT.figure() ax1 = fig.add_subplot(221) line1 = plt.pie(df_14,colors=("g","r")) plt.title('EventLogs') ax1 = fig.add_subplot(223) line2 = plt.pie(df_24,colors=("g","r")) plt.title('InstalledApp') ax1 = fig.add_subplot(222) line3 = plt.pie(df_34,colors=("g","r")) plt.title('Drive') ax1 = fig.add_subplot(224) line4 = plt.pie(df_44,colors=("g","r")) plt.title('SQL Job') ax1 = fig.add_subplot(321) line5 = plt.pie(df_54,colors=("g","r")) plt.title('Administrators') ax2 = fig.add_subplot(212) PLT.show()
-
user3447653 almost 8 yearsThanks, it works perfectly. Is there a way to set a common legend for all the 7 plots? For example, red as "Not healthy", green as "Healthy"?
-
hashcode55 almost 8 yearsYou are looking for
figlegend
, but as each of the plots have their own axes, its not possible to do it withlegend
directly. Or why not just position your legend for one plot? -
user3447653 almost 8 yearsI tried this but not working as expected: lgd = plt.legend((line1), ('Helathy','Not Healthy'), loc='upper right')
-
Josh Friedlander over 5 yearsThis answer, and
subplot2grid
, deserve much more attention. For such a basic task, subplots in Matplotlib are one of the most frustrating things I have to deal with. Bookmarking for future use!