Polar Bar chart using Facetgrid in Python

  facet-grid, python, seaborn

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.

Source: Python Questions

LEAVE A COMMENT