Python 畫雷達圖

qq_40273012發表於2020-12-14
import matplotlib.pyplot as plt
import pandas as pd
from math import pi

df = pd.DataFrame({
    'group': ['A', 'B', 'C', 'D'],
    'var1': [38, 15, 12, 7],
    'var2': [34, 16, 19, 3],
    'var3': [8, 29, 13, 1.4],
    'var4': [17, 31, 23, 24],
    'var5': [18, 35, 22, 4]
})


def make_radar(row, title, color):
    categories = list(df)[1:]  # ['var1', 'var2', 'var3', 'var4', 'var5']
    N = len(categories)  # 5

    angles = [n / float(N) * 2 * pi for n in range(N)]
    angles += angles[:1]#angles[:1]:[0.0]
    #print(angles)#[0.0, 1.2566370614359172, 2.5132741228718345, 3.7699111843077517, 5.026548245743669, 0.0]

    ax = plt.subplot(2, 2, row + 1, polar=True)#ploat=True,繪製極點圖

    ax.set_theta_offset(pi / 2)#ax.set_theta_offset():該方法設定角度偏離
    ax.set_theta_direction(-1)#ax.set_theta_direction():該方法設定極座標的正方向,1:逆時針,-1:順時針,預設逆時針

    plt.xticks(angles[:-1], categories, color='grey', size=8)#改變X座標軸 刻度名稱,顏色,字型大小

    ax.set_rlabel_position(0)#設定極徑標籤顯示位置,0就是沒有偏移
    plt.yticks([10, 20, 30], ["10", "20", "30"], color="grey", size=7)
    plt.ylim(0, 40)#取值範圍

    values = df.loc[row].drop('group').values.flatten().tolist()#flatten()返回一位陣列
    values += values[:1]
    ax.plot(angles, values, color=color, linewidth=2, linestyle='solid')#做折線圖
    ax.fill(angles, values, color=color, alpha=0.4)#做面積圖


    plt.title(title, size=11, color=color, y=1.1)# 新增標題


my_dpi = 96
plt.figure(figsize=(1000 / my_dpi, 1000 / my_dpi), dpi=my_dpi)
my_palette = plt.cm.get_cmap('Set2', len(df.index))#plt.cm.get_cmap():該方法設定畫圖顏色。len(df.index)=4

for row in range(0, len(df.index)):
    make_radar(row=row, title='group' + df['group'][row], color=my_palette(row))

plt.savefig('雷達圖.png')
plt.show()

在這裡插入圖片描述

相關文章