Search code examples
pythonmatplotlibsubplot

Arrangement of pie charts using matplotlib subplot


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()

Solution

  • 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')
    

    enter image description here

    Hope this helps!