使用matplotlib数据可视化,主要画2D图
matplotlib官网:https://matplotlib.org/index.html
一、matplotlib的三层结构
- 1.容器层
canvas(画板层)、figure(画布层)、axes(绘图区/坐标系) - 2.辅助显示层
辅助显示层为axes绘图区内除了根据数据绘制出的图像以外的内容,如网格线、坐标轴标签、刻度、标题、图例等。该层的设置目的为,使得图像能够被用户更加直观的理解,但又不会对图像本身产生实质性的影响。 - 3.图像层
图像层是指axes内通过plot、scatter、bar等函数绘制出的图像。
二、基础绘图
1. matplotlib的中文显示问题(win10)
matplotlib默认字体不支持中文,修改为支持中文即可,解决方法:
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
from matplotlib import font_manager
# 1. 找到fname字体文件的路径,设置想要使用的字体,例如黑体常规:C:\Windows\Fonts\simhei.ttf
font = fm.FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf')
# 2. 显示matplotlib支持的字体,上一步添加好中文字体后,可以找到SimHei
a= sorted([f.name for f in font_manager.fontManager.ttflist])
for i in a:
print(i)
# 3. 应用这个字体后matplotlib就可以显示中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文字体设置
plt.rcParams['axes.unicode_minus'] = False
2.折线图
代码如下(示例):
import matplotlib.pyplot as plt
import random
# 需求:画出某城市11点到12点一小时内每分钟的温度变化折线图,温度范围在15-18度
# 准备数据
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x] # 生成15-18之间均匀分布的随机数,列表生成
# 再添加一个城市的温度变化
y_beijing = [random.uniform(1,3) for i in x]
# 创建画布(容器层)
plt.figure(figsize=(20,10), dpi=(100)) # figsize:figure size画布尺寸, dpi:dots per inch清晰度
# 绘制折线图(图像层)
plt.plot(x, y_shanghai, color='b', linestyle='-.', label='上海')
plt.plot(x, y_beijing, color='m', linestyle=':', label='北京')
# 显示图例
plt.legend(loc='upper left') # location string: 'best','upper right','upper left','lower left','lower right','right','center left'
# 调整x、y轴的刻度
# 准备x轴的刻度说明
x_label = ['11点{}分'.format(i) for i in x]
plt.xticks(x[::5], labels=x_label[::5]) # x,y轴均以步长为5显示,两种表示方法
plt.yticks(range(0,40,5)) # range(),左闭右开
# 添加网格,清晰化图像
plt.grid(True, linestyle='dashdot', alpha=1) # alpha:透明度, linestyle: supported values are '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
# 添加描述信息
plt.xlabel('时间变化')
plt.ylabel('温度变化')
plt.title('某城市11点到12点之间的温度变化')
# 保存图片
# 保存这步须在plt.show这步之前,plt.show会释放整个figure的资源,在显示之后保存只能保存空图片
plt.savefig('figure.svg')
# 显示图像
plt.show()
#%% 多子图显示
import matplotlib.pyplot as plt
import random
# 准备数据
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x] # 生成15-18之间均匀分布的随机数,列表生成
y_beijing = [random.uniform(1,3) for i in x]
# 创建画布,多坐标系显示--plt.subplot()
# figure, axes = plt.subplots(nrows=1, ncols=2, **fig_kw)
figure, axes = plt.subplots(nrows=1, ncols=2, figsize=(20,10), dpi=(100))
# 绘制图像,分别对每个绘图区进行设置,axes[].函数名(),有部分和plt.函数名()不一样
axes[0].plot(x, y_shanghai, color='b', linestyle='-.', label='上海')
axes[1].plot(x, y_beijing, color='m', linestyle=':', label='北京')
# 显示图例
axes[0].legend(loc='upper left')
axes[1].legend(loc='upper right')
# 多个子图自定义x、y轴
# 关于报错:AttributeError: 'AxesSubplot' object has no attribute 'xticks'
x_label = ['11点{}分'.format(i) for i in x]
axes[0].set_xticks(x[::5])
axes[0].set_xticklabels(labels=x_label[::5]) # ***这里需要分成两步传入
axes[0].set_yticks(range(0,40,5))
axes[1].set_xticks(x[::5])
axes[1].set_xticklabels(labels=x_label[::5])
axes[1].set_yticks(range(0,40,5))
# 添加网格,清晰化图像
axes[0].grid(True, linestyle='dashdot', alpha=1)
axes[1].grid(True, linestyle='dashdot', alpha=1)
# 添加描述信息
axes[0].set_xlabel('时间变化')
axes[0].set_ylabel('温度变化')
axes[0].set_title('上海11点到12点之间的温度变化')
axes[1].set_xlabel('时间变化')
axes[1].set_ylabel('温度变化')
axes[1].set_title('北京11点到12点之间的温度变化')
# 显示图像
plt.show()
3. 散点图
代码如下(示例):
# 散点图,查看数据的分布
import matplotlib.pyplot as plt
# 准备数据
x = [225.98, 247.07, 253.14, 457.85, 241.58, 301.01, 20.67, 288.64,
163.56, 120.06, 207.83, 342.75, 147.9 , 53.06, 224.72, 29.51,
21.61, 483.21, 245.25, 399.25, 343.35]
y = [196.63, 203.88, 210.75, 372.74, 202.41, 247.61, 24.9 , 239.34,
140.32, 104.15, 176.84, 288.23, 128.79, 49.64, 191.74, 33.1 ,
30.74, 400.02, 205.35, 330.64, 283.45]
# 创建画布
plt.figure(figsize=(20,10), dpi=100)
# 绘制图像
plt.scatter(x, y)
# 显示图像
plt.show()
4. 柱状图
代码如下(示例):
# 柱状图,同一列别对比,对比同一天下的票房数
import matplotlib.pyplot as plt
# 1、准备数据
movie_names = ['雷神3:诸神黄昏','正义联盟','寻梦环游记']
first_day = [10587.6, 10062, 1275.7]
first_weekend = [36224.9, 34479.6, 11830]
# 创建画布
plt.figure(figsize=(15,10), dpi=100)
# 绘制图像
x = range(len(movie_names))
plt.bar(x, first_day ,width=0.2, color='m', label='首日票房')
plt.bar([i+0.2 for i in x], first_weekend, width=0.2, color='b', label='首周票房')
# 修改图像细节
plt.xticks([i+0.1 for i in x], movie_names, fontsize=20)
plt.legend(fontsize=20)
plt.title('电影票房对比收入')
plt.grid()
plt.show()
5. 饼图
代码如下(示例):
#%% 饼图
import matplotlib.pyplot as plt
# plt.pie(x, labels= , autopct= ,colors), autopct:占比显示指定%1.2f%%
movie_name = ['雷神3:诸神黄昏','正义联盟','东方快车谋杀案','寻梦环游记','全球风暴','降魔传','追捕','七十七天','密战','狂兽','其它']
place_count = [60605,54546,45819,28243,13270,9945,7679,6799,6101,4621,20105]
plt.figure(figsize=(15,10), dpi=100)
plt.pie(place_count, labels=movie_name, autopct='%1.2f%%', colors=['b','r','g','y','c','m','y','k','c','g','y'])
plt.legend()
plt.axis('equal')
plt.show()
6. 直方图
代码如下(示例):
# 直方图,描述数据的频次分布,用于展示大量数据集的统计结果,如中位数、众数、数据是否存在缺口或者异常值
# matplotlib.pyplot.hist(x, bins=None, density=None, **kwargs)
import matplotlib.pyplot as plt
# 准备数据
time = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101,131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]
# 创建画布
plt.figure(figsize=(20, 8), dpi=80)
# 绘制直方图
distance = 2
group_num = (max(time) - min(time))/distance
plt.hist(time, bins=int(group_num), density=True)
plt.xticks(range(min(time), max(time)+2, distance))
plt.grid()
plt.show()