使用polar()绘制雷达图
使用pyplot的polar()函数可以快速绘制雷达图,polar()函数的语法格式如下所示:
polar(theta, r, **kwargs)
该函数常用参数的含义如下:
theta :表示每个数据点所在射线与极径的夹角。
r :表示每个数据点到原点的距离。
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
# 准备数据
dim_num = 6
data = np.array([[0.40, 0.32, 0.35, 0.30, 0.30, 0.88],
[0.85, 0.35, 0.30, 0.40, 0.40, 0.30],
[0.43, 0.89, 0.30, 0.28, 0.22, 0.30],
[0.30, 0.25, 0.48, 0.85, 0.45, 0.40],
[0.20, 0.38, 0.87, 0.45, 0.32, 0.28],
[0.34, 0.31, 0.38, 0.40, 0.92, 0.28]])
angles = np.linspace(0, 2 * np.pi, dim_num, endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
data = np.concatenate((data, [data[0]]))
#维度标签
radar_labels = ['研究型(I)', '艺术型(A)', '社会型(S)',
'企业型(E)', '传统型(C)', '现实型(R)']
radar_labels = np.concatenate((radar_labels, [radar_labels[0]]))
#绘制雷达图
plt.polar(angles, data)
#设置极坐标的标签
plt.thetagrids(angles * 180/np.pi, labels=radar_labels)
#填充多边形
plt.fill(angles, data, alpha=0.25)
# matplotlib中文网 https://www.matplotlib.org.cn/intro/
# 需求一: 请把B同学和C同学的成绩用雷达图展示在同一个绘图区域,并填充不同颜色和透明度
# (只允许调用一次plt.polar和plt.fill)
# B同学成绩: '数学','英语','线代','爬虫','数据可视化','吃喝玩乐' ---> 91,88,83,72,78,26
# C同学成绩: '数学','英语','线代','爬虫','数据可视化','吃喝玩乐' ---> 81,78,85,76,74,36
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
# 0.设置中文
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
# 1.准备大数据专业三位同学各科目成绩
dim_num = 6
radians = np.linspace(0, 2 * np.pi, dim_num, endpoint=False)
radians = np.concatenate((radians, [radians[0]]))
# A同学: '数学','英语','线代','爬虫','数据可视化','吃喝玩乐' ---> 41,38,36,62,68,100
score_a = np.array([41,38,36,62,68,100])
score_a = np.concatenate((score_a, [score_a[0]]))
# B同学:'数学','英语','线代','爬虫','数据可视化','吃喝玩乐' ---> 91,88,83,72,78,26
score_b = np.array([91,88,83,72,78,26])
score_b = np.concatenate((score_b,[score_b[0]]))
# C同学:'数学','英语','线代','爬虫','数据可视化','吃喝玩乐' ---> 81,78,85,76,74,36
score_c = np.array([81,78,85,76,74,36])
score_c = np.concatenate((score_c, [score_c[0]]))
# 2.绘制多边形(雷达图)
#——————————————————————————————————————————
plt.polar(radians,score_a,radians,score_b,radians,score_c)
#——————————————————————————————————————————
# 3.设置维度标签
radar_labels = ['数学','英语','线代','爬虫','数据可视化','吃喝玩乐']
radar_labels = np.concatenate((radar_labels, [radar_labels[0]])) # 拼接一下,构成闭环 (此处可以不拼接,为了统一而已)
# 4.设置极坐标的标签
angles = radians * 180/np.pi # 弧度转角度
plt.thetagrids(angles, labels=radar_labels) # 设置新的刻度标签
# 5.填充多边形
#——————————————————————————————————————————
plt.fill(radians,score_a,radians,score_b,radians,score_c,alpha=0.25)
#——————————————————————————————————————————
# 6.展示图表
plt.show()