三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

python:用matplotlib库生成雷达图

python:用matplotlib库生成雷达图

一,安装第三方库

安装numpy和matplotlib

$ pip install numpy matplotlib

二,代码:

import numpy as np
import matplotlib.pyplot as plt# 1. 准备数据
labels = np.array(['得分', '防守', '篮板', '助攻', '抢断'])
stats = np.array([90, 80, 70, 85, 75])# 2. 计算角度并闭合数据
num_vars = len(labels)
angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
stats = np.concatenate((stats, [stats[0]]))
angles += angles[:1]# 3. 绘图
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = Falseax.plot(angles, stats, color='#1aafbc', linewidth=2)
ax.fill(angles, stats, color='#1aafbc', alpha=0.25)
ax.set_theta_offset(np.pi / 2)
ax.set_theta_direction(-1)
ax.set_thetagrids(np.degrees(angles[:-1]), labels)plt.title('球员能力分布', size=15)# --- 核心修改部分:保存图片 ---
# 可以保存为 .png, .jpg, .pdf, .svg 等格式
plt.savefig('radar_chart.png',   # 文件名dpi=300,            # 分辨率,300是打印级清晰度bbox_inches='tight' # 自动裁剪多余的白边
)print("图片已保存为 radar_chart.png")

三,效果:

image

← 返回列表