在 Python 中使用 Facetgrid 的极坐标条形图

Polar Bar chart using Facetgrid in Python

我正在使用以下代码绘制极坐标条形图:

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

当前的限制是绘图的数量不会针对列 'Type' 的附加值进行缩放。我已尝试使用 FacetGrid 来解决问题(成功率有限):

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

我正在努力解决的问题是:从散点图更改为条形图,set_thetagrids、set_theta_zero_location、set_theta_direction、set_rlabel_position。

任何帮助将不胜感激。谢谢。

我希望我可以像在 R 中一样简单地在 python 中扩展方面的数量。但事实证明它在短时间内太复杂了。因此,我设法使用 'for loop' 来让它工作。希望那里有更简单的解决方案。解决方案如下:

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