前言
pandas的数据处理,基本功能都介绍完了。你都学会了吗?后面我会给大家介绍,数据处理的实战,用例子来把学过的知识点综合应用。这也是我学习Python的方法!数据处理还有一个重要的环节,那就是吧处理好的数据展示出来,对没错那就是我们的Python数据可视化。这篇文章主要介绍Matplotlib库的一些常用技巧。
进群进群:700341555可以获取Python各类入门学习资料!
这是我的微信公众号【Python编程之家】各位大佬用空可以关注下,每天更新Python学习方法,感谢!

导入Matplotlib
就像之前用np作为NumPy的简写形式、pd作为Pandas的简写形式一样,我们也可以在
导入 Matplotlib 时用一些它常用的简写形式。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import matplotlib.pyplot as plt
</pre>
设置绘图样式
我们一般选用plt.style.use()来选择图形的绘图风格。‘classic’是Matplotlib的经典风格。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">plt.style.use('classic')
</pre>
将图形保存为图片
Matplotlib能将图形保存为不同的格式,使用savefig()命令将图形保存为文件。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">fig= plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')
flg.savefig('my_figure.png')
</pre>
在savefig()函数里面,通过不同的扩展名,来决定你要保存图形的格式。Matplotlib支持许多图形格式,你可以通过canvas对象的方法,查看文件格式。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">flg.canvas.get_supported_filetypes()
</pre>
代码结果:
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">{'ps': 'Postscript',
'eps': 'Encapsulated Postscript',
'pdf': 'Portable Document Format',
'pgf': 'PGF code for LaTeX',
'png': 'Portable Network Graphics',
'raw': 'Raw RGBA bitmap',
'rgba': 'Raw RGBA bitmap',
'svg': 'Scalable Vector Graphics',
'svgz': 'Scalable Vector Graphics',
'jpg': 'Joint Photographic Experts Group',
'jpeg': 'Joint Photographic Experts Group',
'tif': 'Tagged Image File Format',
'tiff': 'Tagged Image File Format'}
</pre>
Matplotlib两种画图接口
Matplotlib有两种不同的画图接口:一个是便捷的MATLAB风格接口,另一个是功能更强大的面向对象接口。
1.MATLAB风格接口
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">x= np.linspace(0, 10, 100)
flg= plt.figure() # 创建图形
创建两个子图中的第一个,设置坐标轴
plt.subplot(2, 1, 1) # (行、列、子图编号)
plt.plot(x, np.sin(x))
创建两个子图中的第二个,设置坐标轴
plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x))
</pre>
这种接口特征是:它会持续跟踪“当前的”图形和坐标轴。虽然这个有状态的接口画起图来又快又方便,但是创建第二个子图时,怎么才能回到第一个子图呢?虽然用MATLAB风格接口也能实现,但未免过于复杂,有一种更好的方法!
2.面向对象接口
面向对象接口可以适应更复杂的场景,更好地控制你自己的图形。在面向对象接口中,画图函数不再受到当前“活动”图形或坐标轴的限制,而变成了显式的 Figure 和 Axes 的方法。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># 先创建图形网格
ax是一个包含两个Axes对象的数组
fig, ax= plt.subplots(2)
在每个对象上调用plot()方法
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x));
</pre>
两种方法画简单图形时,选择那种绘制风格主要看个人喜好,不过在画复杂图形时,选择面对对象会好一些简易线形图。
绘制一个简单的图形
在所有图形中,最简单的图形应该就是线性方程y = f (x)的可视化了。要画Matplotlib图形时,都需要先创建一个图形fig和一个坐标轴ax。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
fig= plt.figure()
ax= plt.axes()
</pre>
figure是plt.Figure类的一个实例,可以被看成是一个能够容纳各种坐 标轴、图形、文字和标签的容器。axes是plt.Axes类的一个实例是一个带有刻度和标签的矩形。我们通常用变量fig表示一个图形实例,用变量ax表示一个坐标轴实例或一组坐标轴实例。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">fig= plt.figure()
ax= plt.axes()
x= np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x))
</pre>
创建好坐标轴之后,就可以用 ax.plot 画图了。怎么样可视化还是很简单吧!
调整图形:线条的颜色与风格
我们首先要调整的是:调整它线条的颜色与风格。一般使用plt.plot() 函数的color参数,它支持各种颜色值的字符串。
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">plt.plot(x, np.sin(x-0), color='blue')# 标准颜色名称
plt.plot(x, np.sin(x-1), color='g')# 缩写颜色代码(rgbcmyk)
plt.plot(x, np.sin(x-2), color='0.75')# 范围在0~1的灰度值
plt.plot(x, np.sin(x-3), color='#FFDD44')# 十六进制(RRGGBB,00~FF)
plt.plot(x, np.sin(x-4), color=(1.0,0.2,0.3))# RGB元组,范围在0~1
plt.plot(x, np.sin(x-5), color='chartreuse')# HTML颜色名称
</pre>
linestyle调整线条的风格
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">plt.plot(x, x+0, linestyle='solid')
plt.plot(x, x+1, linestyle='dashed')
plt.plot(x, x+2, linestyle='dashdot')
plt.plot(x, x+3, linestyle='dotted');
你可以用下面的简写形式
plt.plot(x, x+4, linestyle='-') # 实线
plt.plot(x, x+5, linestyle='--') # 虚线
plt.plot(x, x+6, linestyle='-.') # 点划线
plt.plot(x, x+7, linestyle=':'); # 实点线
</pre>
如果你想用简单的方式,可以将 linestyle 和 color 编码组合起来,作为 plt. plot() 函数的一个非关键字参数使用
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">plt.plot(x, x+0, '-g') # 绿色实线
plt.plot(x, x+1, '--c') # 青色虚线
plt.plot(x, x+2, '-.k') # 黑色点划线
plt.plot(x, x+3, ':r'); # 红色实点线
</pre>
调整图形:坐标轴上下限
Matplotlib会自动为你的图形选择最合适的坐标轴上下限,但是有时自定义坐标轴上下限可能会好。调整坐标轴上下限最基础的方法是 plt.xlim() 和 plt.ylim()
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">plt.plot(x, np.sin(x))
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5);
</pre>
plt.axis() 方法可以让你用一行代码设置x和y的限值
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.5])
[-1, 11, -1.5, 1.5]
</pre>
设置图形标签
图形标题与坐标轴标题是最简单的标签,怎样快速设置呢?
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">plt.plot(x, np.sin(x))
plt.title("A Sine Curve")#设置一个标题
plt.xlabel("x")#设置x轴
plt.ylabel("sin(x)")#设置y轴
Text(0,0.5,'sin(x)')
</pre>
网友评论