1. 简要介绍

matplotlib是一个用于画图的Python开源库,提供了强大的画图功能

  • 与MATLAB相比

功能类似,但使用上逊于MATLAB。尤其在数据量很大时,画出的图卡顿很严重,远逊于MATLAB

  • 与Excel相比

如果只画一次图,Excel更好用;但如果想重复画图,还是Python更好用

2. 安装与使用

安装

python3 -m pip install matplotlib

头文件

# !/usr/bin/python3
# -*- coding:utf-8 -*-# 普通二维图
import matplotlib.pyplot as plt# 三维图
import mpl_toolkits.mplot3d

3. 二维图

3.1. 散点图

散点图显示两组数据的值,每一点的坐标位置由变量的值决定。由一组不连接的点完成,用于观察两种变量的相关性

# s 点的面积
# c 点的颜色
# marker 点的形状
# alpha 透明度
plt.scatter(weight, height, s=20, c='b', marker='o')
plt.show()

运行结果见下图

3.2. 折线图

# 生成-10到10之间等间距的100个数
x = np.linspace(-10, 10, 100)
y = x**2plt.plot(x, y)
plt.title("Difference of time between two neighbor frames")
plt.xlabel("time stamps(s)")
plt.ylabel("time diff(s)")
plt.show()

运行结果见下图

# date 是时间格式的数据
plt.plot_data(date, value, '-', color='red', marker='o')
plt.show()

3.3. 条形图

以长方形的长度为变量的计图表,用来比较多个项目分类的数据大小,通常用于数据量较小的数据分析,例如不同季度的销量、不同国家的人口等

3.3.1. 基本用法

N = 5
x = [10, 4, 8, 12, 2]
index = np.arange(N)# 如果想画水平的条形图,则设置orientation='horizontal'或者直接使用plt.barh()
plt.bar(x=index, height=x, color='blue', width=0.8, orientation='vertical')
plt.show()

运行结果见下图

3.3.2. 多组数据

sales_1 = [2, 3, 5, 9, 17]
sales_2 = [4, 9, 10, 1, 1]index = np.arange(5)bar_width = 0.3plt.bar(x=index, height=sales_1, color='blue', width=bar_width)
plt.bar(x=index+bar_width, height=sales_2, color='red', width=bar_width)
plt.show()

运行结果见下图

3.4. 层叠图

sales_1 = [2, 3, 5, 9, 17]
sales_2 = [4, 9, 10, 1, 1]index = np.arange(5)bar_width = 0.3plt.bar(x=index, height=sales_1, color='blue', width=bar_width)
plt.bar(x=index, height=sales_2, color='red', width=bar_width, bottom=sales_1)
plt.show()

运行结果见下图

3.5. 直方图

由一系列高度不等的纵向条形组成,表示数据分布的情况,例如某年级同学的身高分布

3.5.1. 一维直方图

函数

pyplot.hist(x, bins=None, density=None,……kwargs*)

参数说明

属性 说明 类型
x 数据 数值类型
bins 条形数 int
color 颜色 "r","g","y","c"
density 是否以密度的形式显示 bool
range x轴的范围 数值元组(起,终)
bottom y轴的起始位置 数值类型
histtype 线条的类型 "bar":方形,"barstacked":柱形,
"step":"未填充线条"
"stepfilled":"填充线条"
align 对齐方式 "left":左,"mid":中间,"right":右
orientation orientation "horizontal":水平,"vertical":垂直
log 单位是否以科学计术法 bool
rwidth The relative width of the bars as a fraction of the bin width. If None, automatically compute the width. float or None

示例

mu = 100
sigma = 20x = mu + sigma * np.random.randn(2000)
plt.hist(x, bins=10, color='red')
plt.show()

运行结果见下图

3.5.2. 二维直方图

x = np.random.randn(1000) + 2
y = np.random.randn(1000) + 3plt.hist2d(x, y, bins=10)
plt.show()

运行结果见下图

3.6. 饼状图

饼状图显示一个数据系列中各项大小与总和的比例,饼状图中数据点显示为整个饼状图的百分比,例如前十大品牌的市场份额

labels = ['China', 'Japan', 'US', 'UK']
fracs = [40, 30, 20, 10]plt.pie(x=fracs, labels=labels, autopct='%.0f%%')
plt.show()

运行结果见下图

labels = ['China', 'Japan', 'US', 'UK']
fracs = [40, 30, 20, 10]
explode = [0.05, 0, 0, 0]plt.pie(x=fracs, labels=labels, autopct='%.0f%%', explode=explode)
plt.show()

运行结果见下图

3.7. 人机交互

# !/usr/bin/python
# coding: utf-8
import os
import sys
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Imageclass LabelTool:def __init__(self, path):# do somethingdef display(self):fig = plt.figure()img = Image.open(self.path)plt.imshow(img, animated=True)fig.canvas.mpl_connect('press left button of mouse', self.on_press)plt.show()def on_press(self, event):x = event.xdatay = event.ydata

3.8. 显示多张子图

fig = plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(img1)
plt.subplot(1, 2, 2)
plt.imshow(img2)
plt.show()

4. 三维图

Changed in version 1.0.0: Prior to Matplotlib 1.0.0, Axes3D needed to be directly instantiated with from mpl_toolkits.mplot3d import Axes3D; ax = Axes3D(fig).

Changed in version 3.2.0: Prior to Matplotlib 3.2.0, it was necessary to explicitly import the mpl_toolkits.mplot3d module to make the '3d' projection to Figure.add_subplot.

See the mplot3d FAQ for more information about the mplot3d toolkit.

也就是说对不同的版本,以下函数使用上可能略有不同,有的版本需要mpl_toolkits库,有的版本已经集成进去了。

4.1. 曲线

函数

Axes3D.plot(self, xs, ys, *args, zdir='z', **kwargs)

使用

import numpy as np
import matplotlib.pyplot as pltplt.rcParams['legend.fontsize'] = 10fig = 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()

结果

4.2. 散点

函数

Axes3D.scatter(self, xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True, *args, **kwargs)

使用

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) + vminfig = 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()

结果

4.3. 线框

函数

Axes3D.plot_wireframe(self, X, Y, Z, *args, **kwargs)

使用

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as pltfig = 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.4. 曲面

函数

Axes3D.plot_surface(self, X, Y, Z, *args, norm=None, vmin=None, vmax=None, lightsource=None, **kwargs)

使用

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import numpy as npfig, ax = plt.subplots(subplot_kw={"projection": "3d"})# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
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))
# A StrMethodFormatter is used automatically
ax.zaxis.set_major_formatter('{x:.02f}')# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)plt.show()

结果

4.5. 三角化曲面

函数

Axes3D.plot_trisurf(self, *args, color=None, norm=None, vmin=None, vmax=None, lightsource=None, **kwargs)

使用

import matplotlib.pyplot as plt
import numpy as npn_radii = 8
n_angles = 36# 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)[..., np.newaxis]# 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()

结果

4.6. 轮廓

函数

Axes3D.contour(self, X, Y, Z, *args, extend3d=False, stride=5, zdir='z', offset=None, **kwargs)

使用

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

结果

4.7. 填充轮廓

函数

Axes3D.contourf(self, X, Y, Z, *args, zdir='z', offset=None, **kwargs)

使用

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

结果

4.8. 多边形

函数

Axes3D.bar(self, left, height, zs=0, zdir='z', *args, **kwargs)

使用

from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
import numpy as np# Fixing random state for reproducibility
np.random.seed(19680801)def polygon_under_graph(xlist, ylist):"""Construct the vertex list which defines the polygon filling the space underthe (xlist, ylist) line graph.  Assumes the xs are in ascending order."""return [(xlist[0], 0.), *zip(xlist, ylist), (xlist[-1], 0.)]fig = plt.figure()
ax = fig.gca(projection='3d')# Make verts a list such that verts[i] is a list of (x, y) pairs defining
# polygon i.
verts = []# Set up the x sequence
xs = np.linspace(0., 10., 26)# The ith polygon will appear on the plane y = zs[i]
zs = range(4)for i in zs:ys = np.random.rand(len(xs))verts.append(polygon_under_graph(xs, ys))poly = PolyCollection(verts, facecolors=['r', 'g', 'b', 'y'], alpha=.6)
ax.add_collection3d(poly, zs=zs, zdir='y')ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(0, 10)
ax.set_ylim(-1, 4)
ax.set_zlim(0, 1)plt.show()

结果

4.9. 条形图

函数

Axes3D.bar(self, left, height, zs=0, zdir='z', *args, **kwargs)

使用

import matplotlib.pyplot as plt
import numpy as np# Fixing random state for reproducibility
np.random.seed(19680801)fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')colors = ['r', 'g', 'b', 'y']
yticks = [3, 2, 1, 0]
for c, k in zip(colors, yticks):# Generate the random data for the y=k 'layer'.xs = np.arange(20)ys = np.random.rand(20)# You can provide either a single color or an array with the same length as# xs and ys. To demonstrate this, we color the first bar of each set cyan.cs = [c] * len(xs)cs[0] = 'c'# Plot the bar graph given by xs and ys on the plane y=k with 80% opacity.ax.bar(xs, ys, zs=k, zdir='y', color=cs, alpha=0.8)ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')# On the y axis let's only label the discrete values that we have data for.
ax.set_yticks(yticks)plt.show()

结果

4.10. 箭头图

函数

Axes3D.quiver(X, Y, Z, U, V, W, /, length=1, arrow_length_ratio=0.3, pivot='tail', normalize=False, **kwargs)

使用

import matplotlib.pyplot as plt
import numpy as npfig = plt.figure()
ax = fig.gca(projection='3d')# Make the grid
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),np.arange(-0.8, 1, 0.2),np.arange(-0.8, 1, 0.8))# 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.1, normalize=True)plt.show()

结果

4.11. 三维中画二维图

使用

import numpy as np
import matplotlib.pyplot as pltfig = plt.figure()
ax = fig.gca(projection='3d')# Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x, y)')# Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')# Fixing random state for reproducibility
np.random.seed(19680801)x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:c_list.extend([c] * 20)
# By using zdir='y', the y value of these points is fixed to the zs value 0
# and the (x, y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x, z)')# Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')# Customize the view angle so it's easier to see that the scatter points lie
# on the plane y=0
ax.view_init(elev=20., azim=-35)plt.show()

结果

4.12. 文本

函数

Axes3D.text(self, x, y, z, s, zdir=None, **kwargs)

使用

import matplotlib.pyplot as pltfig = plt.figure()
ax = fig.gca(projection='3d')# Demo 1: zdir
zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))
xs = (1, 4, 4, 9, 4, 1)
ys = (2, 5, 8, 10, 1, 2)
zs = (10, 3, 8, 9, 1, 8)for zdir, x, y, z in zip(zdirs, xs, ys, zs):label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir)ax.text(x, y, z, label, zdir)# Demo 2: color
ax.text(9, 0, 0, "red", color='red')# Demo 3: text2D
# Placement 0, 0 would be the bottom left, 1, 1 would be the top right.
ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)# Tweaking display region and labels
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')plt.show()

结果

4.13. 显示多张子图

使用

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as npfrom mpl_toolkits.mplot3d.axes3d import get_test_data# set up a figure twice as wide as it is tall
fig = plt.figure(figsize=plt.figaspect(0.5))#===============
#  First subplot
#===============
# set up the axes for the first plot
ax = fig.add_subplot(1, 2, 1, projection='3d')# plot a 3D surface like in the example mplot3d/surface3d_demo
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
fig.colorbar(surf, shrink=0.5, aspect=10)#===============
# Second subplot
#===============
# set up the axes for the second plot
ax = fig.add_subplot(1, 2, 2, projection='3d')# plot a 3D wireframe like in the example mplot3d/wire3d_demo
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)plt.show()

结果

5. 画多张图

5.1. 多张图独立显示

# first image
plt.figure(1)
plt.hist(frequencies, bins=10, color='red')# second image
plt.figure(2)
plt.plot(time_stamps, time_diffs)# show the two images
plt.show()

5.2. 一张图中显示多张子图

#!/usr/bin/env python
#!encoding=utf-8import matplotlib.pyplot as plt
import numpy as npdef f(t):return np.exp(-t) * np.cos(2 * np.pi * t)if __name__ == '__main__' :t1 = np.arange(0, 5, 0.1)t2 = np.arange(0, 5, 0.02)plt.figure(12)plt.subplot(221)plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')plt.subplot(222)plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')plt.subplot(212)plt.plot([1, 2, 3, 4], [1, 4, 9, 16])plt.show()

6. seaborn

Seaborn是一种基于matplotlib的图形可视化python libraty。它提供了一种高度交互式界面,便于用户能够做出各种有吸引力的统计图表。

Seaborn其实是在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,在大多数情况下使用seaborn就能做出很具有吸引力的图,而使用matplotlib就能制作具有更多特色的图。应该把Seaborn视为matplotlib的补充,而不是替代物。同时它能高度兼容numpypandas数据结构以及scipystatsmodels等统计模式。掌握seaborn能很大程度帮助我们更高效的观察数据与图表,并且更加深入了解它们。

pip3 install seaborn

稍候补充

参考文献

Python数据可视化分析 matplotlib教程_哔哩哔哩_bilibili

https://matplotlib.org/tutorials/toolkits/mplot3d.html

10分钟python图表绘制 | seaborn入门(一):distplot与kdeplot - 知乎

[数据可视化]Seaborn简单介绍 - 简书

matplotlib 绘制多个图形,如何同时独立显示? - 知乎

python使用matplotlib:subplot绘制多个子图 - 我的明天不是梦 - 博客园

matplotlib使用笔记相关推荐

  1. matplotlib学习笔记(3)---热力图(Heat Map)

    matplotlib学习笔记(3)-热力图(Heat Map) import matplotlib.pylab as plt import seaborn as sns import numpy as ...

  2. 【莫烦Python】Matplotlib学习笔记(二)

    [莫烦Python]Matplot学习笔记(一) [莫烦Python]Matplotlib学习笔记(二) 一.Bar柱状图/条形图 二.Contours等高线图 三.Image图像 四.3D图像 五. ...

  3. matplotlib学习笔记 - 散点图、条形图和直方图

    Matplotlib 学习笔记 - 散点图.条形图和直方图 散点图 from matplotlib import pyplot as plt from matplotlib import font_m ...

  4. python可视化:matplotlib学习笔记

    信息可视化是数据分析的一块重要内容.这是一个探索性的过程.比如说,可以帮助我们坚定离群值,或者必要的数据转换,又或者是构建一个理想的模型.对于其他的一些领域,也可以进行web可视化.Python有许多 ...

  5. matplotlib学习笔记.CookBook

    matplotlib 是Python下的一个高质量的画图库,可以简单的类似于MATLAB方法构建高质量的图表. 原始文章地址:http://zanyongli.i.sohu.com/blog/view ...

  6. Matplotlib NumPy笔记

    声明,内容严重借鉴https://blog.csdn.net/weixin_43598956/article/details/106585342 撰写此文目的有二:记录知识点以及练习markdown撰 ...

  7. Matplotlib 学习笔记

    注:该文是上了开智学堂数据科学基础班的课后做的笔记,主讲人是肖凯老师. 数据绘图 数据可视化的原则 为什么要做数据可视化? 为什么要做数据可视化?因为可视化后获取信息的效率高.为什么可视化后获取信息的 ...

  8. matplotlib学习笔记——入门版(超详细)

    最近才肝完的matplotlib入门教程,学习笔记顺便写上.欢迎大家在评论区补充.提问-- print('--------------------------------------------mat ...

  9. python画图matplotlib基础笔记

    numpy~~基础计算库,多维数组处理 scipy~~基于numpy,用于数值计算等等,默认调用intel mkl(高度优化的数学库) pandas~~强大的数据框,基于numpy matplotli ...

  10. matplotlib散点图笔记

    定义: 由一组不连续的点完成的图形 散点图: 包含正相关性,负相关性和不相关性. 散点图生成函数: plt.scatter(x,y) 演示代码如下: import numpy as np import ...

最新文章

  1. Java学习总结:4
  2. cgi、fastcgi、php-cgi、php-fpm的关系
  3. 开启及关闭go mod
  4. php 地图两点距离计算,计算地图上两点间的距离PHP类
  5. 戴尔r720服务器增加内存,dell r720服务器加了一根内存后,开机显示configuring memory,卡在这里进不了系统,请问这是什么情况?...
  6. D3 transtion
  7. 《Windows 8 权威指南》——1.3 引入全新内核休眠模式,实现“瞬间开机”
  8. 201509-2-日期计算
  9. 批量图片处理,打包成zip
  10. linux恢复deleted状态的文件,Linux恢复被删除的文件 How To Recover Deleted Files From Your Linux System ....
  11. amazon aws ip check
  12. word 产生很多temp 不显示_Word与PPT互转,怎样才能30秒内搞定?教程来了
  13. 跨境电商虾皮值不值得做?你了解多少
  14. [转]【总结】clc和clear命令的使用
  15. 本周测试服务器角色转移系统仅开放转入,梦幻西游3月11日更新一览
  16. 程序员如何培养领导力
  17. 【转载】城域网IPv6过渡技术—NAT444与DS-lite详解
  18. html盒模型中border的写法,【前端】盒子模型的边框样式属性和应用技巧讲解
  19. 安卓运行exe文件_【按键精灵教程】RunApp 运行命令
  20. 读Python源码(三)Python列表的表示

热门文章

  1. 国外电子与通信教材系列最新目录单
  2. 前端学习笔记之——使用边框和背景
  3. UVA 202 - Repeating Decimals(模拟)
  4. azkaban短信报警功能和项目依赖功能实现
  5. DirectX11 SDK下载地址
  6. 新浪滚动新闻的json数据获取页面
  7. 新闻网站项目静态页面--详情页
  8. win32gui操作
  9. JVM中的Xms和Xmx
  10. Oracle:Locked by transaction: console [表名]