《Python编程 从入门到实践放弃》 项目二:数据可视化
推荐的数据可视化包
Matplotlib
、Seaborn
、Altair
、Basemap
、Cartopy
、ggplot
本文着重讲Matplotlib, 其他包可以去官网查看原始文档ggplot
和R语言的ggplot2
风格类似,感兴趣的可以自行查阅文档
Matplotlib
可能是 Python 2D-绘图领域使用最广泛的套件。它能让使用者很轻松地将数据图形化,可以轻松实现图表、直方图、功率谱、条形图、误差图、散点图等的绘制,同时提供多样化的输出格式,从而尽可能使容易的事情变得更容易,使困难的事情变成可能。
在Matplotlib
的基础上,还扩展除了大量的第三方软件包 (如绘图:Seaborn
、ggplot
和投影、制图:basemap
和Cartopy
)
"""
@ Tsinlu Lee
@ IDLE (python 3.7.9 64-bits)
@ Emails: liql0429@163.com
@ QQ: 1594996596
@ Spyder: 5.1.5
"""
# -*- coding: utf-8 -*-
## 导入依赖包 ##
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
## 生成数据
x = np.linspace(0, 10, 11); y1 = [3.9, 4.4, 10.8, 10.3, 11.2, 13.1, 14.1, 9.9, 13.9, 15.1, 12.5]
# 这里有一个小tip,在python里;可以用来在同一行写代码,可以提高美化度
# 但是也降低了代码的可读性,所以尽量在不做修改的地方使用
y2 = [y * 2 - 4 for y in y1] # 这里是列表推导式,算是一种很pythonic的表达,感兴趣的可以自行百度
数据可视化部分
fig = plt.figure(figsize = (12,10))
# 绘制画布,画布的大小为12 inch * 10 inch
ax1 = plt.subplot(441)
plt.text(0.1,0.5,"This is the 1st subplot")
# 这是添加文字描述
ax2 = plt.subplot(442)
plt.plot([1,2,3,4],[1,2,3,4])
# 生成线图
ax3 = plt.subplot(443)
plt.plot(x,y1,
color = "green", # 指点线条颜色
linewidth = 1.5, # 指定线条粗细
label = "Line1" # 指定图例信息
)
plt.plot(x,y2,
color = "red", # 指点线条颜色
linewidth = 1.5, # 指定线条粗细
label = "Line2" # 指定图例信息
)
plt.legend(framealpha = 0) # 显示图例
# framealpha = 0 是设置图例边框不可见,更多信息见help(plt.legend)
ax4 = plt.subplot(444)
plt.errorbar(x,y1,np.std(y1),
color = "green", # 指点线条颜色
linewidth = 1.5, # 指定线条粗细
label = "Line1" # 指定图例信息
)
# plt.legend() # 图例会带误差线
## 可以通过增添图例的方法不显示图例
# handles, labels = ax4.get_legend_handles_labels()
# handles = [h[0] for h in handles]
# ax4.legend(handles, labels, loc='upper left',numpoints=1)
## 我这里就不显示了,太多图例会很乱
ax5 = plt.subplot(445)
a, b = np.polyfit(x, y1, deg=1)
y_est = a * x + b
y_err = x.std() * np.sqrt(1/len(x) +
(x - x.mean())**2 / np.sum((x - x.mean())**2))
ax5.plot(x, y_est, '-')
ax5.fill_between(x, y_est - y_err, y_est + y_err, alpha=0.2)
ax5.plot(x, y1, 'o', color='tab:brown') # 这是一种绘制点图的方法
ax6 = plt.subplot(446)
plt.text(0.1,0.5,"This is the 6th subplot")
plt.xticks([]) #关闭x轴标签显示
ax7 = plt.subplot(447)
plt.scatter(x,y1,label = "Scatter1") # 绘制点图
plt.scatter(x,y2,label = "Scatter1") # 绘制点图
plt.legend(framealpha = 0,loc = 2)
# 能看到图像有点重合,我就不调整了
ax8 = plt.subplot(448)
plt.scatter(x,y1,s = [y * 5 for y in y2]) # 骚操作,绘制气泡图
ax9 = plt.subplot(449)
plt.scatter(x,y1,s = [y * 5 for y in y2],
c = y2,marker = "*",cmap = "jet", alpha = 0.6) # 更骚的操作,绘制带颜色带形状的气泡图
ax10 = plt.subplot(4,4,10)
ax10.bar([i - 0.15 for i in x], y1, 0.3)
ax10.bar([i + 0.15 for i in x], y2, 0.3)
ax11 = plt.subplot(4,4,11)
plt.text(0.1,0.5,"This is the 11th subplot")
plt.yticks([]) #关闭y轴标签显示
ax12 = plt.subplot(4,4,12)
ax12.bar(x, y1, 0.3,label = "Y1")
ax12.bar(x, y2, 0.3,alpha = 0.5,label = "Y2")
plt.legend(framealpha = 0)
ax13 = plt.subplot(4,4,13)
ax13.boxplot([y1,y2],
vert=True, # vertical box alignment
patch_artist=True, # fill with color
labels=["Y1","y2"])
ax14 = plt.subplot(4,4,14)
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
pies = ax14.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')
explode = (0, 0.05, 0, 0)
ax15 = plt.subplot(4,2,8)
plt.text(0.1,0.5,"这张图是展示花式生成子图,妙用无穷")
plt.xticks([]) #关闭x轴标签显示
plt.yticks([]) #关闭y轴标签显示
plt.xticks([]) #关闭x轴标签显示
plt.yticks([]) #关闭y轴标签显示
plt.savefig(r"./Matplotlib展示.png",dpi = 540)
plt.show()
# 注意,plt.savefig必须在plt.show前面,因为plt.show每次展示完后会清空画布
参考文件
1、Matplotlib的引文格式为:
2、Matplotlib 官网 (matplotlib.org)
3、[Matplotlib 教程 (runoob.com)](Matplotlib 教程 | 菜鸟教程 (runoob.com))