在 python 中向极坐标图添加标签

Adding label to polar chart in python

我正在为我的情节添加一些标签或注释。我希望标签正好位于绘图和轴角之间。我正在使用“pad = 20”在绘图和轴刻度标签之间创建一个间隙,并使用“label_pos_r”来调整标签的位置。不幸的是,“label_pos_r”取决于数据帧的最大“计数”值,并且这种方法不适用于不同范围的计数值。

有人能告诉我如何使标签的位置 [蓝色] 独立于所使用的数据框吗?有没有办法使用类似“pad = 10”的注释?

我正在使用下面的代码:

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

Row1, Row2, Row3, Row4 = ['A',180,2], ['A',270,6], ['A',360,3], ['B',360,2]
df_polar = pd.DataFrame([Row1, Row2, Row3, Row4]);
df_polar.columns = ['Type', 'Angle', 'Count']

deg = np.pi/180
width = 30*deg
fig = plt.figure() 
fig.set_size_inches((12, 7), 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'] 
   ymax = max(count)

   label_pos_r = ymax + .7

   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.tick_params(direction='out', pad = 20)
   ax.tick_params(axis="y", labelsize=8)
   ax.set_theta_direction(-1)
   ax.set_rlabel_position(15) 
   ax.set_title(Type, fontsize=15)

   ##### Add labels #####
   label_pos_theta = np.array(range(0,346,15)) ; label_val = [1]*len(label_pos_theta)
   dummy_labels = {'Angle': label_pos_theta, 'Labels': label_val}

    
   df2 = pd.DataFrame(dummy_labels)
   df2.columns = ['Angle','Labels']
   df2['Labels'] = df2['Labels'].astype(int) 

   ##########


   for pos, label in zip(df2.Angle, df2.Labels):
    ax.annotate(label, xy=(pos*deg, label_pos_r), xytext=(0, 0), textcoords="offset pixels", 
                color='blue', ha='center', va='center',  fontsize = 8, annotation_clip = False)

        
plt.tight_layout()
plt.show()

根据 Stef 的评论,解决方案是使用:

label_pos_r = ymax * 6.7/6