Python繪制雷達圖(俗稱六芒星)


原文鏈接:https://blog.csdn.net/Just_youHG/article/details/83904618 

背景

《Python數據分析與挖掘實戰》 案例2–航空公司客戶價值分析
在該案例中的雷達圖缺少相應的代碼,查看相關文檔之后,實現的代碼如下。

 

數據
用於作圖的數據對象名為data_cluster,數據展示如下:

注:其中(ZL,ZR,ZF,ZM,ZC)的值表示的是某個簇的聚類中心。

 

繪制 代碼

import numpy as np
import matplotlib.pyplot as plt
def plot_radar(data):
    '''
    the first column of the data is the cluster name;
    the second column is the number of each cluster;
    the last are those to describe the center of each cluster.
    '''
    kinds = data.iloc[:, 0]
    labels = data.iloc[:, 2:].columns
    centers = pd.concat([data.iloc[:, 2:], data.iloc[:,2]], axis=1)
    centers = np.array(centers)
    n = len(labels)
    angles = np.linspace(0, 2*np.pi, n, endpoint=False)
    angles = np.concatenate((angles, [angles[0]]))
    
    fig = plt.figure()
    ax = fig.add_subplot(111, polar=True) # 設置坐標為極坐標
    
    # 畫若干個五邊形
    floor = np.floor(centers.min())     # 大於最小值的最大整數
    ceil = np.ceil(centers.max())       # 小於最大值的最小整數
    for i in np.arange(floor, ceil + 0.5, 0.5):
        ax.plot(angles, [i] * (n + 1), '--', lw=0.5 , color='black')
    
    # 畫不同客戶群的分割線
    for i in range(n):
        ax.plot([angles[i], angles[i]], [floor, ceil], '--', lw=0.5, color='black')
    
    # 畫不同的客戶群所占的大小
    for i in range(len(kinds)):
        ax.plot(angles, centers[i], lw=2, label=kinds[i])
        #ax.fill(angles, centers[i])
    
    ax.set_thetagrids(angles * 180 / np.pi, labels) # 設置顯示的角度,將弧度轉換為角度
    plt.legend(loc='lower right', bbox_to_anchor=(1.5, 0.0)) # 設置圖例的位置,在畫布外
    
    ax.set_theta_zero_location('N')        # 設置極坐標的起點(即0°)在正北方向,即相當於坐標軸逆時針旋轉90°
    ax.spines['polar'].set_visible(False)  # 不顯示極坐標最外圈的圓
    ax.grid(False)                         # 不顯示默認的分割線
    ax.set_yticks([])                      # 不顯示坐標間隔
    
    plt.show()
plot_radar(data_cluster)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM