机器学习—Matplotlib Matplotlib 详细教程:Matplotlib 教程 | 菜鸟教程 (runoob.com)
是专门用于开发2D图表(包括3D图表)
以渐进、交互式方式实现数据可视化
简单的Matplotlib 画图 — 以折线图为例 matplotlib.pyplot模块 matplotlib.pytplot包含了一系列类似于matlab的画图函数。
1 import matplotlib.pyplot as plt
图形绘制流程: 1.创建画布 — plt.figure()
1 2 3 4 plt.figure(figsize=(), dpi=) figsize:指定图的长宽 dpi:图像的清晰度 返回fig对象
2.绘制图像 — plt.plot(x, y)
3.显示图像 — plt.show()
折线图绘制与显示 举例:展现上海一周的天气, 比如从星期一到星期日的天气温度如下:
1 2 3 4 5 6 7 import matplotlib.pyplot as pltplt.figure(figsize=(10 , 10 ), dpi=100 ) plt.plot([1 , 2 , 3 , 4 , 5 , 6 ,7 ], [17 ,17 ,18 ,15 ,11 ,11 ,13 ]) plt.show()
Matplotlib 图像结构
例子:一个完整的流程 我们通过天气温度变化的绘图来融合所有的基础API使用
需求:画出某城市11 点到12 点1 小时内每分钟的温度变化折线图,温度范围在15 度~18 度效果:
准备数据并画出初始折线图 1 2 3 4 5 6 7 8 9 10 11 12 import matplotlib.pyplot as pltimport randomx = range (60 ) y_shanghai = [random.uniform(15 , 18 ) for i in x] plt.figure(figsize=(20 , 8 ), dpi=80 ) plt.plot(x, y_shanghai) plt.show()
添加自定义x,y 刻度
plt.xticks(x, **kwargs)
plt.yticks(y, **kwargs)
1 2 3 4 5 6 7 8 x_ticks_label = ["11点{}分" .format (i) for i in x] y_ticks = range (40 ) plt.xticks(x[::5 ], x_ticks_label[::5 ]) plt.yticks(y_ticks[::5 ])
==ps:如果没有解决过中文问题的话,会显示这个样子:==
中文显示问题解决 解决方案一:
下载中文字体(黑体,看准系统版本)
步骤一:下载 SimHei 字体(或者其他的支持中文显示的字体也行)
步骤二:安装字体
linux下:拷贝字体到 usr/share/fonts 下:
1 sudo cp ~/SimHei.ttf /usr/share/fonts/SimHei.ttf
windows和mac下:双击安装
步骤三:删除~/.matplotlib中的缓存文件
1 2 cd ~/.matplotlib rm -r *
步骤四:修改配置文件matplotlibrc
1 vi ~/.matplotlib/matplotlibrc
将文件内容修改为:
1 2 3 font.family : sans-serif font.sans-serif : SimHei axes.unicode_minus : False
解决方案二:
在Python脚本中动态设置matplotlibrc,这样也可以避免由于更改配置文件而造成的麻烦,具体代码如下:
1 2 3 from pylab import mpl \# 设置显示中文字体 mpl.rcParams["font.sans-serif"] = ["SimHei"]
有时候,字体更改后,会导致坐标轴中的部分字符无法正常显示,此时需要更改axes.unicode_minus参数:
1 2 # 设置正常显示符号 mpl.rcParams["axes.unicode_minus"] = False
添加网格显示 为了更加清楚地观察图形对应的值
1 plt.grid(True , linestyle='--' , alpha=0.5 )
添加描述信息 添加x轴、y轴描述信息及标题
1 2 3 plt.xlabel("时间" ) plt.ylabel("温度" ) plt.title("中午11点0分到12点之间的温度变化图示" , fontsize=20 )
图像保存 # 保存图片到指定路径
注意:plt.show()会释放figure资源,如果在显示图像之后保存图片将只能保存空图片。
完整代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import matplotlib.pyplot as pltimport randomfrom pylab import mplmpl.rcParams["font.sans-serif" ] = ["SimHei" ] mpl.rcParams["axes.unicode_minus" ] = False x = range (60 ) y_shanghai = [random.uniform(15 , 18 ) for i in x] plt.figure(figsize=(20 , 8 ), dpi=100 ) plt.plot(x, y_shanghai) x_ticks_label = ["11点{}分" .format (i) for i in x] y_ticks = range (40 ) plt.xticks(x[::5 ], x_ticks_label[::5 ]) plt.yticks(y_ticks[::5 ]) plt.grid(True , linestyle="--" , alpha=0.5 ) plt.xlabel("时间" ) plt.ylabel("温度" ) plt.title("中午11点--12点某城市温度变化图" , fontsize=20 ) plt.savefig("./test.png" ) plt.show()
例子:在一个坐标系中绘制多个图像 多次plot 需求:再添加一个城市的温度变化
收集到北京当天温度变化情况,温度在1度到3度。怎么去添加另一个在同一坐标系当中的不同图形,其实很简单只需要再次plot 即可,但是需要区分线条,如下显示:
1 2 3 4 5 6 y_beijing = [random.uniform(1 , 3 ) for i in x] plt.plot(x, y_shanghai) plt.plot(x, y_beijing, color='r' , linestyle='--' )
我们仔细观察,用到了两个新的地方,一个是对于不同的折线展示效果,一个是添加图例。
设置图形风格 颜色和线的类型
颜色标记
描述
‘r’
红色
‘g’
绿色
‘b’
蓝色
‘c’
青色
‘m’
品红
‘y’
黄色
‘k’
黑色
‘w’
白色
类型
简写
说明
‘solid’ (默认)
‘-‘
实线
‘dotted’
‘:’
点虚线
‘dashed’
‘—‘
破折线
‘dashdot’
‘-.’
点划线
‘None’
‘’ 或 ‘ ‘
不画线
显示图例 注意:如果只在plt.plot()中设置label还不能最终显示出图例,还需要通过plt.legend()将图例显示出来。
1 2 3 4 5 6 7 plt.plot(x, y_shanghai, label="上海" ) \ plt.plot(x, y_beijing, color='r' , linestyle='--' , label="北京" ) \ plt.legend(loc="best" )
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 x = range (60 ) y_shanghai = [random.uniform(15 , 18 ) for i in x] y_beijing = [random.uniform(1 ,3 ) for i in x] plt.figure(figsize=(20 , 8 ), dpi=100 ) plt.plot(x, y_shanghai, label="上海" ) plt.plot(x, y_beijing, color="r" , linestyle="--" , label="北京" ) x_ticks_label = ["11点{}分" .format (i) for i in x] y_ticks = range (40 ) 54 plt.xticks(x[::5 ], x_ticks_label[::5 ]) plt.yticks(y_ticks[::5 ]) plt.grid(True , linestyle="--" , alpha=0.5 ) plt.xlabel("时间" ) plt.ylabel("温度" ) plt.title("中午11点--12点某城市温度变化图" , fontsize=20 ) plt.savefig("./test.png" ) plt.legend(loc=0 ) plt.show()
例子:多个坐标系显示— plt.subplots( 面向对象的画图方法) 如果我们想要将上海和北京的天气图显示在同一个图的不同坐标系当中,效果如下:
可以通过subplots函数实现(旧的版本中有subplot,使用起来不方便),推荐subplots函数
matplotlib.pyplot.subplots(nrows=1, ncols=1, **fig_kw) 创建一个带有多个axes(坐标系/绘图区)的图
1 2 3 4 5 6 7 8 9 10 11 12 13 Parameters: nrows, ncols : 设置有几行几列坐标系 int , optional, default: 1 , Number of rows/columns of the subplot grid. Returns: fig : 图对象 axes : 返回相应数量的坐标系 设置标题等方法不同: set_xticks set_yticks set_xlabel set_ylabel
关于axes子坐标系的更多方法:参考https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes
注意:plt. 函数名() 相当于面向过程的画图方法,axes.set_ 方法名() 相当于面向对象的画图方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 x = range (60 ) y_shanghai = [random.uniform(15 , 18 ) for i in x] y_beijing = [random.uniform(1 , 5 ) for i in x] fig, axes = plt.subplots(nrows=1 , ncols=2 , figsize=(20 , 8 ), dpi=100 ) axes[0 ].plot(x, y_shanghai, label="上海" ) axes[1 ].plot(x, y_beijing, color="r" , linestyle="--" , label="北京" ) x_ticks_label = ["11点{}分" .format (i) for i in x] y_ticks = range (40 ) axes[0 ].set_xticks(x[::5 ]) axes[0 ].set_yticks(y_ticks[::5 ]) axes[0 ].set_xticklabels(x_ticks_label[::5 ]) axes[1 ].set_xticks(x[::5 ]) axes[1 ].set_yticks(y_ticks[::5 ]) axes[1 ].set_xticklabels(x_ticks_label[::5 ]) axes[0 ].grid(True , linestyle="--" , alpha=0.5 ) axes[1 ].grid(True , linestyle="--" , alpha=0.5 ) axes[0 ].set_xlabel("时间" ) axes[0 ].set_ylabel("温度" ) axes[0 ].set_title("中午11点--12点某城市温度变化图" , fontsize=20 ) axes[1 ].set_xlabel("时间" ) axes[1 ].set_ylabel("温度" ) axes[1 ].set_title("中午11点--12点某城市温度变化图" , fontsize=20 ) plt.savefig("./test.png" ) axes[0 ].legend(loc=0 ) axes[1 ].legend(loc=0 ) plt.show()
折线图的应用场景
呈现公司产品(不同区域)每天活跃用户数
呈现app每天下载数量
呈现产品新功能上线后,用户点击次数随时间的变化
拓展:画各种数学函数图像
注意:plt.plot()除了可以画折线图,也可以用于画各种数学函数图像
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import numpy as npx = np.linspace(-10 , 10 , 1000 ) y = np.sin(x) plt.figure(figsize=(20 , 8 ), dpi=100 ) plt.plot(x, y) plt.grid() plt.show()
小结
添加x,y轴刻度
plt.xticks()
plt.yticks()
注意: 在传递进去的第一个参数必须是数字, 不能是字符串, 如果是字符串吗, 需要进行替换操作
添加网格显示
plt.grid(linestyle=”—“, alpha=0.5)
添加描述信息
plt.xlabel()
plt.ylabel()
plt.title()
图像保存
多次plot
显示图例
plt.legend(loc=”best”)
注意: 一定要在plt.plot() 里面设置一个label, 如果不设置, 没法显示
多个坐标系显示
plt.subplots(nrows=, ncols=)
折线图的应用
1.应用于观察数据的变化
2.可是画出一些数学函数图像