matplotlib实际上是一个面向对象的绘图库,它所绘制的图表元素均对应一个对象。matplotlib官方提供了3种API分别为:
(1) 使用pyplot模块开发的接口:pyplot API
(2)面向对象的接口:object-oriented API
(3)使用pylab模块开发的接口:pylab API
而使用matplotlib可绘制的简单图表有plot()折线图、bar()柱形图、barh()条形图、stackplot()堆积面积图、hist()直方图、pie()饼图、scatter()散点图、boxplot()箱形图、polar()雷达图、errorbar()误差棒图
一、使用面向对象API绘制雷达图
import numpy as np
import matplotlib.pyplot as plt
# 数据
categories = ['A', 'B', 'C', 'D', 'E'] values = [4, 2, 5, 3, 1]
# 创建一个子图和极坐标系
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
# 计算角度
angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False).tolist() angles += angles[:1]
# 绘制雷达图
ax.plot(angles, values, color='r', linewidth=2)
ax.fill(angles, values, color='r', alpha=0.25)
# 设置刻度
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories)
# 设置标题
ax.set_title('Radar Chart')
# 显示图形
plt.show()
示例:霍华德职业兴趣测试
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(angles, score_a,radians,score_b,radians,score_c,radians ,alpha=0.25)
# 6.展示图表
plt.show()