Search code examples
pythonseabornfacet-grid

Polar Bar chart using Facetgrid in Python


I am plotting a polar bar chart using the following code:

import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 


Row1, Row2, Row3 = ['A',180,2], ['A',270,6], ['A',360,3]

df_polar = pd.DataFrame([Row1, Row2, Row3]) 
df_polar.columns = ['Type', 'Angle', 'Count']
df_polar = df_polar.set_index('Angle')

deg = np.pi/180 
Angle =  np.array(df_polar.index.tolist()) 
theta = Angle = Angle * deg 

count = radii = df_polar['Count'] 
width = 30*deg 
colors = plt.cm.viridis(df_polar['Count'] / 4.)

ax = plt.subplot(111, projection='polar') 
ax.bar(theta, count, width=width, bottom=0, color=colors, alpha=.6)
ax.set_thetagrids(range(0, 360, 30)) 
ax.set_theta_zero_location("N") # Set 0 degrees to the top of the plot 
ax.set_theta_direction(-1) 
ax.set_rlabel_position(15) 
plt.show()

The current limitation is that the number of plots does not scale for additional values for Column 'Type'. I have attempted to use FacetGrid to solve the issue (with limited success):

import numpy as np
import pandas as pd
import seaborn as sns

sns.set()

Row1, Row2, Row3 , Row4 = ['A',180,2], ['A',270,6], ['A',360,3] , ['B',360,3]

df_polar = pd.DataFrame([Row1, Row2, Row3, Row4])
df_polar.columns = ['Type', 'Angle', 'Count']

# Generate an example radial datast
df = df_polar

# Set up a grid of axes with a polar projection
ax = sns.FacetGrid(df, col="Type", hue="Type",
                  subplot_kws=dict(projection='polar'), height=4.5,
                  sharex=False, sharey=False, despine=False)

# Draw a scatterplot onto each axes in the grid
ax.map(sns.scatterplot, "Angle", "Count")  

What I am struggling with are: changing from a scatter to a barplot, set_thetagrids, set_theta_zero_location, set_theta_direction, set_rlabel_position.

Any help will be greatly appreciated. Thank you.


Solution

  • I was hoping that I could scale number of facets in python as simply as I do in R. But it turned out of be too complex in the short time scale. Therefore I managed to make it work using a 'for loop' instead. Hopefully there is simpler solution out there. Solution posted below:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd 
    
    Row1, Row2, Row3, Row4, Row5 = ['A',180,2], ['A',270,6], ['A',360,3], ['B',360,5], ['C',135,6]
    
    
    df_polar = pd.DataFrame([Row1, Row2, Row3, Row4, Row5])
    df_polar.columns = ['Type', 'Angle', 'Count']
    
    deg = np.pi/180
    width = 30*deg
        
    fig = plt.figure()
    fig.set_size_inches((15, 9), forward=False)
    
    i=0
    x = np.array(df_polar['Type']) 
    Total_types = np.unique(x)
        
        
    for Type in Total_types:
       
        i+=1
        df_plot = df_polar[df_polar['Type'] == Type].set_index('Angle')
              
        Angle =  np.array(df_plot.index.tolist())
        theta = Angle = Angle * deg
     
        count = radii = df_plot['Count'] 
        colors = plt.cm.viridis(df_plot['Count'] / 4.)
    
        ax = fig.add_subplot(1,len(Total_types),i, projection='polar')
        ax.bar(theta, count, width=width, bottom=0, color=colors, alpha=.6)
        ax.set_thetagrids(range(0, 360, 30))
        ax.set_theta_zero_location("N") 
        ax.set_theta_direction(-1)
        ax.set_rlabel_position(15) 
        ax.set_title(Type, fontsize=15)
        
        
    plt.tight_layout()
    plt.show()