python机器学习-Python MatPlotLib

作者 : 慕源网 本文共11634个字,预计阅读时间需要30分钟 发布时间: 2021-10-19 共421人阅读

本文是Python 机器学习系列的一部分。您可以在此处找到本系列之前所有帖子的链接

在上一章中,我们研究了 Python Scikit-Learn、它的函数和它的 Python 实现。

在本章中,我们将从下一个非常有用且重要的 Python 机器学习库“Python MatPlotLib”开始。

什么是 MatPlotLib?

Matplotlib 是 Python 编程语言及其数值数学扩展 NumPy 的绘图库。它提供了一个面向对象的 API,用于使用 Tkinter、wxPython、Qt 或 GTK+ 等通用 GUI 工具包将绘图嵌入到应用程序中。还有一个基于状态机(如 OpenGL)的程序化“pylab”接口,其设计与 MATLAB 非常相似,但不鼓励使用它。SciPy 使用 Matplotlib。

Matplotlib 最初由 John D. Hunter 编写,拥有活跃的开发社区,并在 BSD 风格的许可下分发。它于 2003 年首次发布,官方网站是www.matplotlib.org。

什么是 Matplotlib PyPlot?

matplotlib.pyplot 是一组命令样式函数,它们使 matplotlib 像 MATLAB 一样工作。每个 pyplot 函数都会对图形进行一些更改

例如,创建图形,在图形中创建绘图区域,在绘图区域中绘制一些线条,用标签装饰绘图等。

在 matplotlib.pyplot 中,函数调用中保留了各种状态,以便它跟踪当前图形和绘图区域等内容,并且绘图函数指向当前轴(请注意此处和大多数位置的“轴”)文档是指图形的部分,而不是用于多个轴的严格数学术语)。

什么是Matplotlib Inline?

在使用jupyter notebook 或者 jupyter qtconsole的时候,才会经常用到%matplotlib,也就是说那一份代码可能就是别人使用jupyter notebook 或者 jupyter qtconsole进行编辑的。而%matplotlib具体作用是当你调用matplotlib.pyplot的绘图函数plot()进行绘图的时候,或者生成一个figure画布的时候,可以直接在你的python console里面生成图像。

安装 Matplotlib

1. Ubuntu/Linux

sudo apt update -y                
sudo apt upgrade -y                
sudo apt install python3-tk python3-pip -y                
sudo pip install matplotlib -y  

2. Anaconda Prompt

conda install -c conda-forge matplotlib 

1. 特点

该图形跟踪所有子轴、少量“特殊”artists(标题、图形图例等)和canvas。 一个图形可以有任意数量的 Axes,但要有用,至少应该有一个。

2. Axes

这就是您认为的“绘图”,它是具有数据空间的图像区域。一个给定的图形可以包含多个 Axes,但一个给定的 Axes 对象只能在一个 Figure 中。Axes 包含两个(在 3D 的情况下为三个)Axis 对象(注意AxesAxis之间的区别),它们负责处理数据限制(数据限制也可以通过 set_xlim() 和 set_ylim 来控制()轴方法)。每个轴都有一个标题(通过 set_title() 设置)、一个 x 标签(通过 set_xlabel() 设置)和一个通过 set_ylabel() 设置的 y 标签。

Axes 类及其成员函数是使用 OO 接口的主要入口点。

3. Axis

这些是类似数轴的对象。他们负责设置图形限制并生成刻度(axis上的标记)和刻度标签(标记刻度的字符串)。刻度的位置由 Locator 对象确定,刻度标签字符串由 Formatter 格式化。正确的定位器和格式器的组合可以非常精细地控制刻度位置和标签。

4. Artist

基本上,您可以在图形上看到的所有内容都是artist (甚至Figure、Axes和Axis 对象)。这包括 Text 对象、Line2D 对象、集合对象、Patch 对象……(你懂的)。当图形被渲染时,所有的artists 都被绘制到canvas。大多数Artists 都与 Axes 相关联;这样的Artists 不能被多个 Axes 共享或从一个轴移动到另一个轴。

笔记:

这里有几个工具包可以扩展 python matplotlib 功能。其中一些是单独的下载,另一些可以与 matplotlib 源代码一起提供,但具有外部依赖项。

  • Basemap:这是一个地图绘制工具包,具有各种地图投影、海岸线和政治边界。
  • Cartopy:它是一个映射库,具有面向对象的地图投影定义,以及任意点、线、多边形和图像转换功能。
  • Excel tools:Matplotlib 提供了用于与 Microsoft Excel 交换数据的实用程序。
  • Mplot3d:用于 3-D 绘图。
  • Natgrid:它是natgrid库的接口,用于对间隔数据进行不规则网格化。

Mayplotlib 中的后端(Backend )是什么?

Matplotlib 针对许多不同的用例和输出格式。有些人从 python shell 交互式地使用 matplotlib,并在他们键入命令时弹出绘图窗口。有些人运行 Jupyter notebook 并绘制内联图以进行快速数据分析。有些人在批处理脚本中使用 matplotlib 从数值模拟中生成 postscript 图像,还有一些人运行 Web 应用程序服务器来动态提供图形。

为了支持所有这些用例,matplotlib 可以针对不同的输出,这些功能中的每一个都称为后端(backend);“frontend”是面向用户的代码,即绘图代码,而“后端”则在幕后完成所有艰苦的工作来制作图形。

有两种类型的后端:用户界面后端(用于 pygtk、wxpython、tkinter、qt4 或 macosx;也称为“交互式后端”)和用于制作图像文件的硬拷贝后端(PNG、SVG、PDF、PS;也称为“非交互式后端”)。

以下是后端(Backend )渲染器列表

Backend 描述
Qt5Agg Qt5 画布中的 Agg 渲染(需要 PyQt5)。这个后端可以在 IPython 中使用 %matplotlib qt5 激活。
ipympl 嵌入在 Jupyter 小部件中的 Agg 渲染。(需要ipympl)。可以使用 %matplotlib ipympl 在 Jupyter notebook 中启用此后端。
GTK3Agg Agg 渲染到 GTK 3.x 画布(需要 PyGObject,以及 pycairo 或 cairocffi)。这个后端可以在 IPython 中使用 %matplotlib gtk3 激活。
GTK3Agg Agg 在 OSX 中渲染成 Cocoa 画布。这个后端可以在 IPython 中使用 %matplotlib osx 激活。
TkAgg Agg 渲染到 Tk 画布(需要 TkInter)。这个后端可以在 IPython 中使用 %matplotlib tk 激活。
nbAgg 在 Jupyter 经典笔记本中嵌入交互式图形。这个后端可以通过 %matplotlib notebook 在 Jupyter notebooks 中启用。
WebAgg 在 show() 将启动一个带有交互式图形的龙卷风服务器。
GTK3Cairo Cairo 渲染到 GTK 3.x 画布(需要 PyGObject,以及 pycairo 或 cairocffi)。
Qt4Agg Agg 渲染到 Qt4 画布(需要 PyQt4 或 pyside)。这个后端可以在 IPython 中使用 %matplotlib qt4 激活。
WXAgg Agg 渲染到 wxWidgets 画布(需要 wxPython 4)。这个后端可以在 IPython 中使用 %matplotlib wx 激活。

绘制二维图形

二维或二维图是那些只有 2 个轴即 x 和 y 的图,它们是平面图

1. 线二维图

折线图或折线图或折线图或曲线图是一种将信息显示为由直线段连接的称为“标记”的一系列数据点的图表。它是许多领域中常见的一种基本类型的图表。

import matplotlib.pyplot as plt   
    
# x axis values   
x = [1,2,3]   
# corresponding y axis values   
y = [3,1,2]   
    
# plotting the points    
plt.plot(x, y)   
    
# naming the x axis   
plt.xlabel('x - axis')   
# naming the y axis   
plt.ylabel('y - axis')   
    
# giving a title to my graph   
plt.title('2D Line Plot!')   
    
# function to show the plot   
plt.show()    

输出 

2. 自定义二维绘图

自定义 2D 图是可以以图形方式增强的图

import matplotlib.pyplot as plt   
  
# x axis values   
x = [1,2,3,4,5,6]   
# corresponding y axis values   
y = [2,4,1,5,2,6]   
  
# plotting the points   
plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,   
        marker='o', markerfacecolor='blue', markersize=12)   
  
# setting x and y axis range   
plt.ylim(1,8)   
plt.xlim(1,8)   
  
# naming the x axis   
plt.xlabel('x - axis')   
# naming the y axis   
plt.ylabel('y - axis')   
  
# giving a title to my graph   
plt.title('Custom Plots!')   
  
# function to show the plot   
plt.show()   

输出

3. 条形二维图

条形图或条形图是一种图表或图形,它用矩形条显示分类数据,矩形条的高度或长度与其所代表的值成正比。条形可以垂直或水平绘制。垂直条形图有时也称为折线图。

import matplotlib.pyplot as plt   
  
# x-coordinates of left sides of bars   
left = [1, 2, 3, 4, 5]   
  
# heights of bars   
height = [10, 20, 30, 40, 50]   
  
# labels for bars   
tick_label = ['one', 'two', 'three', 'four', 'five']   
  
# plotting a bar chart   
plt.bar(left, height, tick_label = tick_label,   
        width = 0.8, color = ['blue', 'green', 'red','yellow','black'])   
  
# naming the x-axis   
plt.xlabel('x - axis')   
# naming the y-axis   
plt.ylabel('y - axis')   
# plot title   
plt.title('bar chart!')   
  
# function to show the plot   
plt.show()   

输出

4.直方图二维图

直方图是数字数据分布的准确表示。它是对连续变量概率分布的估计,由 Karl Pearson 首次引入。它与条形图不同,条形图关联两个变量,而直方图只关联一个变量。

import matplotlib.pyplot as plt   
  
# frequencies   
ages = [2,5,70,40,30,45,50,45,43,40,44,   
        60,7,13,57,18,90,77,32,21,20,40]   
  
# setting the ranges and no. of intervals   
range = (0, 100)   
bins = 5  
  
# plotting a histogram   
plt.hist(ages, bins, range, color ='red',   
        histtype = 'bar', rwidth = 0.8)   
  
# x-axis label   
plt.xlabel('age')   
# frequency label   
plt.ylabel('No. of people')   
# plot title   
plt.title('My histogram')   
  
# function to show the plot   
plt.show() 

输出

5. 散点二维图

散点图是一种绘图或数学图,使用笛卡尔坐标显示一组数据的典型两个变量的值。如果点被编码,则可以显示一个额外的变量

import matplotlib.pyplot as plt   
  
# x-axis values   
x = [2,4,5,7,6,8,9,11,12,12]  
# y-axis values   
y = [1,2,3,4,5,6,7,8,9,10]  
  
# plotting points as a scatter plot   
plt.scatter(x, y, label= "stars", color= "green",   
            marker= "x", s=30)   
  
# x-axis label   
plt.xlabel('x - axis')   
# frequency label   
plt.ylabel('y - axis')   
# plot title   
plt.title('Scatter plot!')   
# showing legend   
plt.legend()   
  
# function to show the plot   
plt.show()   

输出

6. 饼图二维图

饼图是一种圆形统计图形,它被分成多个切片以说明数字比例。在饼图中,每个切片的弧长与其代表的数量成正比。

import matplotlib.pyplot as plt   
  
# defining labels   
activities = ['eat', 'sleep', 'work', 'play']   
  
# portion covered by each label   
slices = [3, 7, 8, 6]   
  
# color for each label   
colors = ['r', 'y', 'g', 'b']   
  
# plotting the pie chart   
plt.pie(slices, labels = activities, colors=colors,   
        startangle=90, shadow = True, explode = (0.3, 0, 0.1, 0),   
        radius = 1.2, autopct = '%1.1f%%')   
  
# plotting legend   
plt.legend()   
  
# showing the plot   
plt.show()   

输出

绘制 3D 图形

工具包是扩展 Matplotlib 的特定于应用程序的函数的集合。

mplot3d

mplot3d 工具包通过提供可以创建 3D 场景的 2D 投影的轴对象,为 matplotlib 添加了简单的 3D 绘图功能。生成的图形将具有与常规 2D 绘图相同的外观和感觉。

1. 线 3D 绘图

折线图或折线图或折线图或曲线图是一种将信息显示为由直线段连接的称为“标记”的一系列数据点的图表。它是许多领域中常见的一种基本类型的图表。

# This import registers the 3D projection but is otherwise unused.  
from mpl_toolkits.mplot3d import Axes3D  #F401 unused import  
  
import numpy as np  
import matplotlib.pyplot as plt  
  
  
plt.rcParams['legend.fontsize'] = 10  
  
fig = plt.figure()  
ax = fig.gca(projection='3d')  
  
# Prepare arrays x, y, z  
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)  
z = np.linspace(-2, 2, 100)  
r = z**2 + 1  
x = r * np.sin(theta)  
y = r * np.cos(theta)  
  
ax.plot(x, y, z, label='parametric curve')  
ax.legend()  
  
plt.show()  

输出

2. 散点图 3D 图

散点图是一种绘图或数学图,使用笛卡尔坐标显示一组数据的典型两个变量的值。如果点被编码,则可以显示一个额外的变量

# This import registers the 3D projection but is otherwise unused.  
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import  
  
import matplotlib.pyplot as plt  
import numpy as np  
  
# Fixing random state for reproducibility  
np.random.seed(19680801)  
  
  
def randrange(n, vmin, vmax):  
    ''''' 
    Helper function to make an array of random numbers having shape (n, ) 
    with each number distributed Uniform(vmin, vmax). 
    '''  
    return (vmax - vmin)*np.random.rand(n) + vmin  
  
fig = plt.figure()  
ax = fig.add_subplot(111, projection='3d')  
  
n = 100  
  
# For each set of style and range settings, plot n random points in the box  
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].  
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:  
    xs = randrange(n, 23, 32)  
    ys = randrange(n, 0, 100)  
    zs = randrange(n, zlow, zhigh)  
    ax.scatter(xs, ys, zs, marker=m)  
  
ax.set_xlabel('X Label')  
ax.set_ylabel('Y Label')  
ax.set_zlabel('Z Label')  
  
plt.show()  

输出

3. 线框 3D 绘图

线框图采用值网格并将其投影到指定的三维表面上,并且可以使生成的三维形式非常容易可视化。

from mpl_toolkits.mplot3d import axes3d  
import matplotlib.pyplot as plt  
  
  
fig = plt.figure()  
ax = fig.add_subplot(111, projection='3d')  
  
# Grab some test data.  
X, Y, Z = axes3d.get_test_data(0.05)  
  
# Plot a basic wireframe.  
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)  
  
plt.show()  

输出

4. 表面 3D 绘图

曲面图是三维数据的图表。表面图不是显示单个数据点,而是显示指定因变量 (Y) 和两个自变量(X 和 Z)之间的函数关系。该图是等高线图的配套图。

# This import registers the 3D projection but is otherwise unused.  
from mpl_toolkits.mplot3d import Axes3D  # F401 unused import  
  
import matplotlib.pyplot as plt  
from matplotlib import cm  
from matplotlib.ticker import LinearLocator, FormatStrFormatter  
import numpy as np  
  
  
fig = plt.figure()  
ax = fig.gca(projection='3d')  
  
# Make data.  
X = np.arange(-5, 5, 0.5)  
Y = np.arange(-5, 5, 0.5)  
X, Y = np.meshgrid(X, Y)  
R = np.sqrt(X**2 + Y**2)  
Z = np.sin(R)  
  
# Plot the surface.  
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,  
                       linewidth=0, antialiased=False)  
  
# Customize the z axis.  
ax.set_zlim(-1.01, 1.01)  
ax.zaxis.set_major_locator(LinearLocator(10))  
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))  
  
# Add a color bar that maps values to colors.  
fig.colorbar(surf, shrink=0.5, aspect=5)  
  
plt.show() 

输出

5. 三曲面 3D 绘图

紧凑曲面的三角剖分是覆盖曲面的有限三角形集合,曲面上的每个点都在一个三角形中,并且任何两个三角形的交点要么是空的,要么是公共边,要么是公共顶点. 三角面称为三角面。

from mpl_toolkits.mplot3d import Axes3D  
import matplotlib.pyplot as plt  
import numpy as np  
  
  
n_radii = 16  
n_angles = 16  
  
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).  
radii = np.linspace(0.125, 1.0, n_radii)  
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)  
  
# Repeat all angles for each radius.  
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)  
  
# Convert polar (radii, angles) coords to cartesian (x, y) coords.  
# (0, 0) is manually added at this stage,  so there will be no duplicate  
# points in the (x, y) plane.  
x = np.append(0, (radii*np.cos(angles)).flatten())  
y = np.append(0, (radii*np.sin(angles)).flatten())  
  
# Compute z to make the pringle surface.  
z = np.sin(-x*y)  
  
fig = plt.figure()  
ax = fig.gca(projection='3d')  
  
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)  
  
plt.show()  

输出

6. 等高线 3D 绘图

两个变量的函数的等高线是一条曲线,沿着该曲线该函数具有恒定值,因此该曲线连接等值的点。它是平行于平面的函数 f 的三维图的平面截面。等高线图是一种通过在二维格式上绘制恒定 z 切片(称为等高线)来表示 3 维表面的图形技术。也就是说,给定 z 值,绘制线条以连接出现该 z 值的 (x,y) 坐标。

from mpl_toolkits.mplot3d import axes3d  
import matplotlib.pyplot as plt  
from matplotlib import cm  
  
fig = plt.figure()  
ax = fig.gca(projection='3d')  
X, Y, Z = axes3d.get_test_data(0.005)  
cset = ax.contour(X, Y, Z, extend3d=True, cmap=cm.coolwarm)  
ax.clabel(cset, fontsize=9, inline=1)  
  
plt.show()  

输出

7. 填充轮廓 3D 图

这是一种等高线图,其中填充了每个 3D artist

从 mpl_toolkits.mplot3d 导入 axes3d  
导入 matplotlib.pyplot 作为 plt  
从 matplotlib 导入 cm  
  
fig = plt.figure()  
ax = fig.gca(projection= '3d' )  
X, Y, Z = axes3d.get_test_data( 0.005 )  
cset = ax.contourf(X, Y, Z, cmap=cm.coolwarm)  
ax.clabel(cset, fontsize= 9 , inline= 1 )  
  
plt.show()  

输出

8. 多边形 3D 绘图

多边形图是一种 3D 图,其中artists 可以具有不同的形状和大小,对任何artists 的形状或大小没有限制

from mpl_toolkits.mplot3d import Axes3D  
from matplotlib.collections import PolyCollection  
import matplotlib.pyplot as plt  
from matplotlib import colors as mcolors  
import numpy as np  
  
  
fig = plt.figure()  
ax = fig.gca(projection='3d')  
  
  
def cc(arg):  
    return mcolors.to_rgba(arg, alpha=0.9)  
  
xs = np.arange(0, 10, 0.2)  
verts = []  
zs = [0.0, 1.0, 2.0, 3.0]  
for z in zs:  
    ys = np.random.rand(len(xs))  
    ys[0], ys[-1] = 0, 0  
    verts.append(list(zip(xs, ys)))  
  
poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'),  
                                         cc('y')])  
poly.set_alpha(0.9)  
ax.add_collection3d(poly, zs=zs, zdir='y')  
  
ax.set_xlabel('X')  
ax.set_xlim3d(0, 10)  
ax.set_ylabel('Y')  
ax.set_ylim3d(-1, 4)  
ax.set_zlabel('Z')  
ax.set_zlim3d(0, 1)  
  
plt.show()  

输出

9.条形3D图

条形图或条形图是一种图表或图形,它用矩形条显示分类数据,矩形条的高度或长度与其所代表的值成正比。条形可以垂直或水平绘制。垂直条形图有时也称为折线图。

from mpl_toolkits.mplot3d import Axes3D  
import matplotlib.pyplot as plt  
import numpy as np  
  
fig = plt.figure()  
ax = fig.add_subplot(111, projection='3d')  
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):  
    xs = np.arange(100)  
    ys = np.random.rand(100)  
  
    # You can provide either a single color or an array. To demonstrate this,  
    # the first bar of each set will be colored cyan.  
    cs = [c] * len(xs)  
    cs[0] = 'c'  
    ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)  
  
ax.set_xlabel('X')  
ax.set_ylabel('Y')  
ax.set_zlabel('Z')  
  
plt.show()  

输出 

10.Quiver 3D

quiver 图将速度向量显示为箭头,在点 (x,y) 处具有分量 (u,v)。

from mpl_toolkits.mplot3d import axes3d  
import matplotlib.pyplot as plt  
import numpy as np  
  
fig = plt.figure()  
ax = fig.gca(projection='3d')  
  
# Make the grid  
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.4),  
                      np.arange(-0.8, 1, 0.3),  
                      np.arange(-0.8, 1, 0.3))  
  
# Make the direction data for the arrows  
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)  
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)  
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *  
     np.sin(np.pi * z))  
  
ax.quiver(x, y, z, u, v, w, length=0.2, normalize=True)  
  
plt.show()  

输出

结论

在本章中,我们学习了 Python MatPlotLib。在下一章中,我们将学习 Python Seaborn。

Python Seaborn 是一个基于 Python MatPlotLib 的 Python 数据可视化库。它提供了一个高级界面,用于绘制有吸引力且信息丰富的统计图形。


慕源网 » python机器学习-Python MatPlotLib

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录