【问题标题】:Create a radar chart for every index position in df为 df 中的每个索引位置创建一个雷达图
【发布时间】:2022-11-27 11:02:45
【问题描述】:

我的数据框看起来与此类似:

df = pd.DataFrame({"Name": ["A", "B", "C", "D", "E","F", "G"],
                    "Tldiffto3": [2.0, -3.0, 2.0,17.0,7.0, 
                      12.0,2.0],
                    "LZdiffto3": [0.94, -5.0, 7.0,29.0,4.0, 
                      10.0,2.5],
                    "SZdiffto3": [0.94, -5.0, 7.0,29.0,4.0, 
                      10.0,2.5],
                    "KZdiffto3": [0.8, -9.0, 10.0,8.0,3.0, 
                      11.0,4.5]})

以下代码创建单个雷达图:

# number of variables
categories=list(df)[0:]

N = len(categories)
# create angle by dividing the plot / number of variable
angles = [n / float(N) * 2 * pi for n in range(N)]
angles += angles[:1]

values = 
df.loc[df.index[0]].values.flatten().tolist()
values += values[:1]

fig, ax = plt.subplots(figsize=(6, 6), 
          subplot_kw=dict(polar=True), dpi = 100)

   # Draw the outline of the data.
  ax.plot(angles, values, color='#1aaf6c', linewidth=1, 
        )
  # add the fill in  
  ax.fill(angles, values, color='#1aaf6c', alpha=0.25) 

# Fix axis to go in the right order and start at 12 o'clock.
ax.set_theta_offset(np.pi / 2)
ax.set_theta_direction(-1)

现在我想遍历索引并为每个索引创建一个带有雷达图的新子图,即名称:

for i in range(df.index):
  ax.plot(angles, values, color='#1aaf6c', linewidth=1) 
  ax.fill(angles, values, color='#1aaf6c', alpha=0.25) 

这不起作用,不确定问题出在哪里,希望得到解释 :)

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:

    问题是它每次都会覆盖图,除非您创建新的子图。我还使用了fig.tight_layout() 来避免重叠。您可以调整 nrowsncolumns 以获得更好的视图:

    fig, ax = plt.subplots(nrows=len(df), ncols=1, figsize=(20, 12), 
                  subplot_kw=dict(polar=True), dpi = 100)
    fig.tight_layout()
    
    for i in range(len(df)):
        values =  df.loc[df.index[i]].values.flatten().tolist()
        values += values[:1]
    
         # Draw the outline of the data.
        ax[i].plot(angles, values, color='#1aaf6c', linewidth=1, 
              )
        # add the fill in  
        ax[i].fill(angles, values, color='#1aaf6c', alpha=0.25) 
    
        # Fix axis to go in the right order and start at 12 o'clock.
        ax[i].set_theta_offset(np.pi / 2)
        ax[i].set_theta_direction(-1)
    

    输出:

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 2016-02-21
      • 2020-10-22
      • 2021-10-31
      • 2018-12-30
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 2014-03-06
      相关资源
      最近更新 更多