在Python中使用Facetgrid的极坐标图

坦吉尔

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

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

当前的限制是,图的数量无法根据“类型”列的其他值进行缩放。我尝试使用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循环”代替它。希望那里有更简单的解决方案。解决方案如下:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章