Python绘制雷达图(俗称六芒星)

本文介绍如何使用Python绘制航空公司客户价值分析的雷达图,包括数据准备、代码实现及图表美化过程。通过具体案例展示了从数据到可视化图表的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

《Python数据分析与挖掘实战》 案例2–航空公司客户价值分析
在该案例中的雷达图缺少相应的代码,查看相关文档之后,实现的代码如下。

数据

用于作图的数据对象名为data_cluster,数据展示如下:
在这里插入图片描述
:其中(ZL,ZR,ZF,ZM,ZC)的值表示的是某个簇的聚类中心。

绘制

代码
import numpy as np
from matplotlib.pyplot import 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_padar(data_cluster)

在这里插入图片描述

后记

未进行美化的雷达图如下:
  • 注释了对极坐标更改的设置
#ax.set_theta_zero_location('N')        # 设置极坐标的起点(即0°)在正北方向,即相当于坐标轴逆时针旋转90°
#ax.spines['polar'].set_visible(False)  # 不显示极坐标最外圈的圆
#ax.grid(False)                         # 不显示默认的分割线
#ax.set_yticks([])                      # 不显示坐标间隔
  • 效果图
    在这里插入图片描述
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值