1. 介绍Matplotlib 是一个功能强大的 Python 库用于创建各种类型的图表和可视化。无论您是数据科学家、工程师还是研究人员Matplotlib 都可以帮助您以直观的方式探索数据并传达结果。在本文中我们将提供一个完整的指南介绍如何使用 Matplotlib 创建基本的图表包括折线图、散点图、柱状图和饼图。与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.mplot3d3. 二维图3.1. 散点图散点图显示两组数据的值每一点的坐标位置由变量的值决定。由一组不连接的点完成用于观察两种变量的相关性# s 点的面积 # c 点的颜色 # marker 点的形状 # alpha 透明度 plt.scatter(weight, height, s20, cb, markero) plt.show()运行结果见下图3.2. 折线图# 生成-10到10之间等间距的100个数 x np.linspace(-10, 10, 100) y x**2 plt.plot(x, y) plt.title(Difference of time between two neighbor frames) plt.xlabel(time stamps(s)) plt.ylabel(time diff(s)) plt.axis(equal) # 设置两个轴的尺度相同 plt.show()运行结果见下图# date 是时间格式的数据 plt.plot_data(date, value, -, colorred, markero) plt.show()3.3. 条形图以长方形的长度为变量的计图表用来比较多个项目分类的数据大小通常用于数据量较小的数据分析例如不同季度的销量、不同国家的人口等3.3.1. 基本用法N 5 x [10, 4, 8, 12, 2] index np.arange(N) # 如果想画水平的条形图则设置orientationhorizontal或者直接使用plt.barh() plt.bar(xindex, heightx, colorblue, width0.8, orientationvertical) 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.3 plt.bar(xindex, heightsales_1, colorblue, widthbar_width) plt.bar(xindexbar_width, heightsales_2, colorred, widthbar_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.3 plt.bar(xindex, heightsales_1, colorblue, widthbar_width) plt.bar(xindex, heightsales_2, colorred, widthbar_width, bottomsales_1) plt.show()运行结果见下图3.5. 直方图由一系列高度不等的纵向条形组成表示数据分布的情况例如某年级同学的身高分布3.5.1. 一维直方图函数pyplot.hist(x, binsNone, densityNone,……kwargs*)参数说明属性说明类型x数据数值类型bins条形数intcolor颜色r, g, y, cdensity是否以密度的形式显示boolrangex轴的范围数值元组起终bottomy轴的起始位置数值类型histtype线条的类型bar方形barstacked柱形step未填充线条stepfilled填充线条align对齐方式left左mid中间right右orientationorientationhorizontal水平vertical垂直log单位是否以科学计术法boolrwidthThe relative width of the bars as a fraction of the bin width. IfNone, automatically compute the width.float or None示例mu 100 sigma 20 x mu sigma * np.random.randn(2000) plt.hist(x, bins10, colorred) plt.show()运行结果见下图3.5.2. 二维直方图x np.random.randn(1000) 2 y np.random.randn(1000) 3 plt.hist2d(x, y, bins10) plt.show()运行结果见下图3.6. 饼状图饼状图显示一个数据系列中各项大小与总和的比例饼状图中数据点显示为整个饼状图的百分比例如前十大品牌的市场份额labels [China, Japan, US, UK] fracs [40, 30, 20, 10] plt.pie(xfracs, labelslabels, autopct%.0f%%) plt.show()运行结果见下图labels [China, Japan, US, UK] fracs [40, 30, 20, 10] explode [0.05, 0, 0, 0] plt.pie(xfracs, labelslabels, autopct%.0f%%, explodeexplode) 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 Image class LabelTool: def __init__(self, path): # do something def display(self): fig plt.figure() img Image.open(self.path) plt.imshow(img, animatedTrue) fig.canvas.mpl_connect(press left button of mouse, self.on_press) plt.show() def on_press(self, event): x event.xdata y event.ydata3.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 withfrom 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, zdirz, **kwargs)使用import numpy as np import matplotlib.pyplot as plt plt.rcParams[legend.fontsize] 10 fig plt.figure() ax fig.gca(projection3d) # 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, labelparametric curve) ax.legend() plt.show()结果4.2. 散点函数Axes3D.scatter(self, xs, ys, zs0, zdirz, s20, cNone, depthshadeTrue, *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) vmin fig plt.figure() ax fig.add_subplot(111, projection3d) 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, markerm) 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 plt fig plt.figure() ax fig.add_subplot(111, projection3d) # Grab some test data. X, Y, Z axes3d.get_test_data(0.05) # Plot a basic wireframe. ax.plot_wireframe(X, Y, Z, rstride10, cstride10) plt.show()结果4.4. 曲面函数Axes3D.plot_surface(self, X, Y, Z, *args, normNone, vminNone, vmaxNone, lightsourceNone, **kwargs)使用import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np fig, 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, cmapcm.coolwarm, linewidth0, antialiasedFalse) # 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, shrink0.5, aspect5) plt.show()结果4.5. 三角化曲面函数Axes3D.plot_trisurf(self, *args, colorNone, normNone, vminNone, vmaxNone, lightsourceNone, **kwargs)使用import matplotlib.pyplot as plt import numpy as np n_radii 8 n_angles 36 # Make radii and angles spaces (radius r0 omitted to eliminate duplication). radii np.linspace(0.125, 1.0, n_radii) angles np.linspace(0, 2*np.pi, n_angles, endpointFalse)[..., 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(projection3d) ax.plot_trisurf(x, y, z, linewidth0.2, antialiasedTrue) plt.show()结果4.6. 轮廓函数Axes3D.contour(self, X, Y, Z, *args, extend3dFalse, stride5, zdirz, offsetNone, **kwargs)使用from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib import cm fig plt.figure() ax fig.gca(projection3d) X, Y, Z axes3d.get_test_data(0.05) # Plot contour curves cset ax.contour(X, Y, Z, cmapcm.coolwarm) ax.clabel(cset, fontsize9, inlineTrue) plt.show()结果4.7. 填充轮廓函数Axes3D.contourf(self, X, Y, Z, *args, zdirz, offsetNone, **kwargs)使用from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib import cm fig plt.figure() ax fig.gca(projection3d) X, Y, Z axes3d.get_test_data(0.05) cset ax.contourf(X, Y, Z, cmapcm.coolwarm) ax.clabel(cset, fontsize9, inlineTrue) plt.show()结果4.8. 多边形函数Axes3D.bar(self, left, height, zs0, zdirz, *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 under the (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(projection3d) # 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, zszs, zdiry) 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, zs0, zdirz, *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, projection3d) colors [r, g, b, y] yticks [3, 2, 1, 0] for c, k in zip(colors, yticks): # Generate the random data for the yk 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 yk with 80% opacity. ax.bar(xs, ys, zsk, zdiry, colorcs, alpha0.8) ax.set_xlabel(X) ax.set_ylabel(Y) ax.set_zlabel(Z) # On the y axis lets 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, /, length1, arrow_length_ratio0.3, pivottail, normalizeFalse, **kwargs)使用import matplotlib.pyplot as plt import numpy as np fig plt.figure() ax fig.gca(projection3d) # 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, length0.1, normalizeTrue) plt.show()结果4.11. 三维中画二维图使用import numpy as np import matplotlib.pyplot as plt fig plt.figure() ax fig.gca(projection3d) # 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, zs0, zdirz, labelcurve 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 zdiry, 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, zs0, zdiry, cc_list, labelpoints 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 its easier to see that the scatter points lie # on the plane y0 ax.view_init(elev20., azim-35) plt.show()结果4.12. 文本函数Axes3D.text(self, x, y, z, s, zdirNone, **kwargs)使用import matplotlib.pyplot as plt fig plt.figure() ax fig.gca(projection3d) # 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, colorred) # 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, transformax.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 np from mpl_toolkits.mplot3d.axes3d import get_test_data # set up a figure twice as wide as it is tall fig plt.figure(figsizeplt.figaspect(0.5)) # # First subplot # # set up the axes for the first plot ax fig.add_subplot(1, 2, 1, projection3d) # 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, rstride1, cstride1, cmapcm.coolwarm, linewidth0, antialiasedFalse) ax.set_zlim(-1.01, 1.01) fig.colorbar(surf, shrink0.5, aspect10) # # Second subplot # # set up the axes for the second plot ax fig.add_subplot(1, 2, 2, projection3d) # 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, rstride10, cstride10) plt.show()结果5. 画多张图5.1. 多张图独立显示# first image plt.figure(1) plt.hist(frequencies, bins10, colorred) # second image plt.figure(2) plt.plot(time_stamps, time_diffs) # show the two images plt.show()5.2. 一张图中显示多张子图#!/usr/bin/env python #!encodingutf-8 import matplotlib.pyplot as plt import numpy as np def 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()5.3. 控制子图的尺寸import os import cv2 from matplotlib.gridspec import GridSpec from matplotlib.patches import FancyArrow, Polygon, Circle import matplotlib.pyplot as plt gs GridSpec(3, 3) fig plt.figure(figsize(48, 27), dpi40, tight_layoutTrue) ax fig.add_subplot(gs[0, 0]) image_path os.path.join(xxx.png) image cv2.imread(image_path) ax.imshow(image) ax fig.add_subplot(gs[1:, :]) ax.grid(on) ax.set_aspect(equal) ax.set_title(image titile) ax.set_xlim(-30, 100) ax.set_ylim(-30, 30) x points[:, 0] y points[:, 1] ax.scatter( points[:, 0], points[:, 1], s2, marker., colorcolors alpha0.3, )6. seabornSeaborn是一种基于matplotlib的图形可视化python libraty。它提供了一种高度交互式界面便于用户能够做出各种有吸引力的统计图表。Seaborn其实是在matplotlib的基础上进行了更高级的API封装从而使得作图更加容易在大多数情况下使用seaborn就能做出很具有吸引力的图而使用matplotlib就能制作具有更多特色的图。应该把Seaborn视为matplotlib的补充而不是替代物。同时它能高度兼容numpy与pandas数据结构以及scipy与statsmodels等统计模式。掌握seaborn能很大程度帮助我们更高效的观察数据与图表并且更加深入了解它们。pip3 install seaborn6.1. 依赖库import matplotlibimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationimport pandas as pdimport seaborn as sns6.2. 散点图拟合趋势线图绘制线性回归图k 2b 3x np.random.rand(160) noise np.random.randn(160) / 3y x * k b noise df pd.DataFrame() df[abscissa] x df[ordinate] y sns.lmplot(xabscissa, yordinate, datadf) plt.title(Liner: y kx b) plt.show()6.2. 线图使用lineplot可以绘制有多种语义分组可能性的线图filename seaborn-data/tips.csv tips pd.read_csv(filename) sns.lineplot(xday, ytotal_bill, datatips) plt.show()6.3. 条形图使用barplot可以将点估计和误差显示为矩形条条形图。filename seaborn-data/tips.csvtips pd.read_csv(filename) print(tips) sns.barplot(xday, ytotal_bill, datatips, huesex) plt.show()6.4. 直方图使用histplot绘制单变量或双变量直方图以显示数据集的分布。filename seaborn-data/tips.csvtips pd.read_csv(filename) print(tips) sns.histplot(xtotal_bill, datatips, huesex, kdeTrue) plt.show()参考文献Python数据可视化分析 matplotlib教程_哔哩哔哩_bilibilihttps://matplotlib.org/tutorials/toolkits/mplot3d.html10分钟python图表绘制 | seaborn入门一distplot与kdeplot - 知乎[数据可视化]Seaborn简单介绍 - 简书matplotlib 绘制多个图形如何同时独立显示 - 知乎python使用matplotlib:subplot绘制多个子图 - 我的明天不是梦 - 博客园推荐一个替代matlab的免费画图软件