Matplotlib

一 简介:

Matplotlib是一个Python 2D绘图库,它可以在各种平台上以各种硬拷贝格式和交互式环境生成出具有出版品质的图形。 Matplotlib可用于Python脚本,Python和IPython shell,Jupyter笔记本,Web应用程序服务器和四个图形用户界面工具包

Matplotlib试图让简单的事情变得更简单,让无法实现的事情变得可能实现。 只需几行代码即可生成绘图,直方图,功率谱,条形图,错误图,散点图等。 有关示例,请参阅示例图和缩略图库。

为了简单绘图,pyplot模块提供了类似于MATLAB的界面,特别是与IPython结合使用时。 对于高级用户,您可以通过面向对象的界面或MATLAB用户熟悉的一组函数完全控制线条样式,字体属性,轴属性等。

二 相关文档:

三 入门与进阶案例

1- 简单图形绘制

根据坐标点绘制:

import numpy as np

import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5,6,7,8])

y = np.array([3,5,7,6,2,6,10,15])

plt.plot(x,y,'r')# 折线 1 x 2 y 3 color

plt.plot(x,y,'g',lw=10)# 4 line w

# 折线 饼状 柱状

x = np.array([1,2,3,4,5,6,7,8])

y = np.array([13,25,17,36,21,16,10,15])

plt.bar(x,y,0.2,alpha=1,color='b')# 5 color 4 透明度 3 0.9

plt.show()

传入参数是numpy数组时的效果:

import numpy as np

import matplotlib.pyplot as plt

for i in range(0,15):

# 1 柱状图

dateOne = np.zeros([2])

dateOne[0] = i;

dateOne[1] = i;

y = np.zeros([2])

y[0] = 10

y[1] = 20

plt.plot(dateOne,y,'r',lw=8)

plt.show()

根据函数图像绘制:

# -*- coding: utf-8 -*-

"""

简单图形绘制

"""

import matplotlib.pyplot as plt

import numpy as np

#从-1-----1之间等间隔采66个数.也就是说所画出来的图形是66个点连接得来的

#注意:如果点数过小的话会导致画出来二次函数图像不平滑

x = np.linspace(-1, 1,66)

# 绘制y=2x+1函数的图像

y = 2 * x + 1

plt.plot(x, y)

plt.show()

# 绘制x^2函数的图像

y = x**2

plt.plot(x, y)

plt.show()

2- figure的简单使用

# -*- coding: utf-8 -*-

"""

figure的使用

"""

import matplotlib.pyplot as plt

import numpy as np

#

x = np.linspace(-1, 1, 50)

# figure 1

y1 = 2 * x + 1

plt.figure()

plt.plot(x, y1)

# figure 2

y2 = x**2

plt.figure()

plt.plot(x, y2)

# figure 3,指定figure的编号并指定figure的大小, 指定线的颜色, 宽度和类型

#一个坐标轴上画了两个图形

y2 = x**2

plt.figure(num = 5, figsize = (4, 4))

plt.plot(x, y1)

plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')

plt.show()

一共会画出三张图,前两张和上面的简单案例画出来的两张一样。第三张:

3- 设置坐标轴

# -*- coding: utf-8 -*-

"""

设置坐标轴

"""

import matplotlib.pyplot as plt

import numpy as np

# 绘制普通图像

x = np.linspace(-1, 1, 50)

y1 = 2 * x + 1

y2 = x**2

plt.figure()

plt.plot(x, y1)

plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')

# 设置坐标轴的取值范围

plt.xlim((-1, 1))

plt.ylim((0, 3))

# 设置坐标轴的lable

#标签里面必须添加字体变量:fontproperties='SimHei',fontsize=14。不然可能会乱码

plt.xlabel(u'这是x轴',fontproperties='SimHei',fontsize=14)

plt.ylabel(u'这是y轴',fontproperties='SimHei',fontsize=14)

# 设置x坐标轴刻度, 之前为0.25, 修改后为0.5

#也就是在坐标轴上取5个点,x轴的范围为-1到1所以取5个点之后刻度就变为0.5了

plt.xticks(np.linspace(-1, 1, 5))

plt.show()

上面代码的基础上加上下面代码(直接加载最后一句代码前面即可):

# 获取当前的坐标轴, gca = get current axis

ax = plt.gca()

# 设置右边框和上边框

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

# 设置x坐标轴为下边框

ax.xaxis.set_ticks_position('bottom')

# 设置y坐标轴为左边框

ax.yaxis.set_ticks_position('left')

# 设置x轴, y周在(0, 0)的位置

ax.spines['bottom'].set_position(('data', 0))

ax.spines['left'].set_position(('data', 0))

如果在上面代码的最后一句之前加上下面的代码:

# 设置坐标轴label的大小,背景色等信息

for label in ax.get_xticklabels() + ax.get_yticklabels():

label.set_fontsize(12)

label.set_bbox(dict(facecolor = 'green', edgecolor = 'None', alpha = 0.7))

4- 设置legend图例

# -*- coding: utf-8 -*-

"""

设置坐标轴

"""

import matplotlib.pyplot as plt

import numpy as np

# 绘制普通图像

x = np.linspace(-1, 1, 50)

y1 = 2 * x + 1

y2 = x**2

plt.figure()

plt.plot(x, y1)

plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--')

# 设置坐标轴的取值范围

plt.xlim((-1, 1))

plt.ylim((0, 3))

# 设置坐标轴的lable

#标签里面必须添加字体变量:fontproperties='SimHei',fontsize=14。不然可能会乱码

plt.xlabel(u'这是x轴',fontproperties='SimHei',fontsize=14)

plt.ylabel(u'这是y轴',fontproperties='SimHei',fontsize=14)

# 设置x坐标轴刻度, 之前为0.25, 修改后为0.5

#也就是在坐标轴上取5个点,x轴的范围为-1到1所以取5个点之后刻度就变为0.5了

plt.xticks(np.linspace(-1, 1, 5))

# 获取当前的坐标轴, gca = get current axis

ax = plt.gca()

# 设置右边框和上边框

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

# 设置x坐标轴为下边框

ax.xaxis.set_ticks_position('bottom')

# 设置y坐标轴为左边框

ax.yaxis.set_ticks_position('left')

# 设置x轴, y周在(0, 0)的位置

ax.spines['bottom'].set_position(('data', 0))

ax.spines['left'].set_position(('data', 0))

plt.show()

5- 添加注解和绘制点以及在图形上绘制线或点

# -*- coding: utf-8 -*-

"""

添加注解和绘制点以及在图形上绘制线或点

"""

import matplotlib.pyplot as plt

import numpy as np

# 绘制普通图像

x = np.linspace(-3, 3, 50)

y = 2 * x + 1

plt.figure()

plt.plot(x, y)

# 将上、右边框去掉

ax = plt.gca()

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

# 设置x轴的位置及数据在坐标轴上的位置

ax.xaxis.set_ticks_position('bottom')

ax.spines['bottom'].set_position(('data', 0))

# 设置y轴的位置及数据在坐标轴上的位置

ax.yaxis.set_ticks_position('left')

ax.spines['left'].set_position(('data', 0))

# 定义(x0, y0)点

x0 = 1

y0 = 2 * x0 + 1

# 绘制(x0, y0)点

plt.scatter(x0, y0, s = 50, color = 'blue')

# 绘制虚线

plt.plot([x0, x0], [y0, 0], 'k--', lw = 2.5)

# 绘制注解一

plt.annotate(r'$2 * x + 1 = %s$' % y0, xy = (x0, y0), xycoords = 'data', xytext = (+30, -30), \

textcoords = 'offset points', fontsize = 16, arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3, rad = .2'))

# 绘制注解二

plt.text(-3, 3, r'$Test\ text. \mu \sigma_i, \alpha_i$', fontdict = {'size': 16, 'color': 'red'})

plt.show()

6- 绘制散点图

# -*- coding: utf-8 -*-

"""

绘制散点图

"""

import numpy as np

import matplotlib.pyplot as plt

# 数据个数

n = 1024

# 均值为0, 方差为1的随机数

x = np.random.normal(0, 1, n)

y = np.random.normal(0, 1, n)

# 计算颜色值

color = np.arctan2(y, x)

# 绘制散点图

plt.scatter(x, y, s = 75, c = color, alpha = 0.5)

# 设置坐标轴范围

plt.xlim((-1.5, 1.5))

plt.ylim((-1.5, 1.5))

# 不显示坐标轴的值

plt.xticks(())

plt.yticks(())

plt.show()

7- 绘制柱状图

# -*- coding: utf-8 -*-

"""

绘制柱状图

"""

import matplotlib.pyplot as plt

import numpy as np

# 数据数目

n = 10

x = np.arange(n)

# 生成数据, 均匀分布(0.5, 1.0)之间

y1 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)

y2 = (1 - x / float(n)) * np.random.uniform(0.5, 1.0, n)

# 绘制柱状图, 向上

plt.bar(x, y1, facecolor = 'blue', edgecolor = 'white')

# 绘制柱状图, 向下

plt.bar(x, -y2, facecolor = 'green', edgecolor = 'white')

temp = zip(x, y2)

# 在柱状图上显示具体数值, ha水平对齐, va垂直对齐

for x, y in zip(x, y1):

plt.text(x + 0.05, y + 0.1, '%.2f' % y, ha = 'center', va = 'bottom')

for x, y in temp:

plt.text(x + 0.05, -y - 0.1, '%.2f' % y, ha = 'center', va = 'bottom')

# 设置坐标轴范围

plt.xlim(-1, n)

plt.ylim(-1.5, 1.5)

# 去除坐标轴

plt.xticks(())

plt.yticks(())

plt.show()

8- 绘制登高线图

# -*- coding: utf-8 -*-

"""

绘制登高线图

"""

import matplotlib.pyplot as plt

import numpy as np

# 定义等高线高度函数

def f(x, y):

return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)

# 数据数目

n = 256

# 定义x, y

x = np.linspace(-3, 3, n)

y = np.linspace(-3, 3, n)

# 生成网格数据

X, Y = np.meshgrid(x, y)

# 填充等高线的颜色, 8是等高线分为几部分

plt.contourf(X, Y, f(X, Y), 8, alpha = 0.75, cmap = plt.cm.hot)

# 绘制等高线

C = plt.contour(X, Y, f(X, Y), 8, colors = 'black', linewidth = 0.5)

# 绘制等高线数据

plt.clabel(C, inline = True, fontsize = 10)

# 去除坐标轴

plt.xticks(())

plt.yticks(())

plt.show()

9- 绘制Image

# -*- coding: utf-8 -*-

"""

绘制Image

"""

import matplotlib.pyplot as plt

import numpy as np

# 定义图像数据

a = np.linspace(0, 1, 9).reshape(3, 3)

# 显示图像数据

plt.imshow(a, interpolation = 'nearest', cmap = 'bone', origin = 'lower')

# 添加颜色条

plt.colorbar()

# 去掉坐标轴

plt.xticks(())

plt.yticks(())

plt.show()

10- 绘制3D图形

# -*- coding: utf-8 -*-

"""

绘制3d图形

"""

import matplotlib.pyplot as plt

import numpy as np

from mpl_toolkits.mplot3d import Axes3D

# 定义figure

fig = plt.figure()

# 将figure变为3d

ax = Axes3D(fig)

# 数据数目

n = 256

# 定义x, y

x = np.arange(-4, 4, 0.25)

y = np.arange(-4, 4, 0.25)

# 生成网格数据

X, Y = np.meshgrid(x, y)

# 计算每个点对的长度

R = np.sqrt(X ** 2 + Y ** 2)

# 计算Z轴的高度

Z = np.sin(R)

# 绘制3D曲面

ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = plt.get_cmap('rainbow'))

# 绘制从3D曲面到底部的投影

ax.contour(X, Y, Z, zdim = 'z', offset = -2, cmap = 'rainbow')

# 设置z轴的维度

ax.set_zlim(-2, 2)

plt.show()

11- subplot绘制多图

# -*- coding: utf-8 -*-

"""

subplot绘制多图

"""

import matplotlib.pyplot as plt

plt.figure()

# 绘制第一个图

plt.subplot(2, 2, 1)

plt.plot([0, 1], [0, 1])

# 绘制第二个图

plt.subplot(2, 2, 2)

plt.plot([0, 1], [0, 1])

# 绘制第三个图

plt.subplot(2, 2, 3)

plt.plot([0, 1], [0, 1])

# 绘制第四个图

plt.subplot(2, 2, 4)

plt.plot([0, 1], [0, 1])

plt.show()

# -*- coding: utf-8 -*-

"""

subplot绘制多图

"""

import matplotlib.pyplot as plt

plt.figure()

# 绘制第一个图

plt.subplot(2, 1, 1)

plt.plot([0, 1], [0, 1])

# 绘制第二个图

plt.subplot(2, 3, 4)

plt.plot([0, 1], [0, 1])

# 绘制第三个图

plt.subplot(2, 3, 5)

plt.plot([0, 1], [0, 1])

# 绘制第四个图

plt.subplot(2, 3, 6)

plt.plot([0, 1], [0, 1])

plt.show()

12- figure绘制多图

# -*- coding: utf-8 -*-

"""

figure绘制多图

"""

# -*- coding: utf-8 -*-

"""

figure绘制多图

"""

import matplotlib.pyplot as plt

# 定义figure

plt.figure()

# figure分成3行3列, 取得第一个子图的句柄, 第一个子图跨度为1行3列, 起点是表格(0, 0)

ax1 = plt.subplot2grid((3, 3), (0, 0), colspan = 3, rowspan = 1)

ax1.plot([0, 1], [0, 1])

ax1.set_title('Test')

# figure分成3行3列, 取得第二个子图的句柄, 第二个子图跨度为1行3列, 起点是表格(1, 0)

ax2 = plt.subplot2grid((3, 3), (1, 0), colspan = 2, rowspan = 1)

ax2.plot([0, 1], [0, 1])

# figure分成3行3列, 取得第三个子图的句柄, 第三个子图跨度为1行1列, 起点是表格(1, 2)

ax3 = plt.subplot2grid((3, 3), (1, 2), colspan = 1, rowspan = 1)

ax3.plot([0, 1], [0, 1])

# figure分成3行3列, 取得第四个子图的句柄, 第四个子图跨度为1行3列, 起点是表格(2, 0)

ax4 = plt.subplot2grid((3, 3), (2, 0), colspan = 3, rowspan = 1)

ax4.plot([0, 1], [0, 1])

plt.show()

# -*- coding: utf-8 -*-

"""

figure绘制多图

"""

import matplotlib.pyplot as plt

import matplotlib.gridspec as gridspec

# 定义figure

plt.figure()

# 分隔figure

gs = gridspec.GridSpec(3, 3)

ax1 = plt.subplot(gs[0, :])

ax2 = plt.subplot(gs[1, 0:2])

ax3 = plt.subplot(gs[1, 2])

ax4 = plt.subplot(gs[2, :])

# 绘制图像

ax1.plot([0, 1], [0, 1])

ax1.set_title('Test')

ax2.plot([0, 1], [0, 1])

ax3.plot([0, 1], [0, 1])

ax4.plot([0, 1], [0, 1])

plt.show()

13- figure图的嵌套

# -*- coding: utf-8 -*-

"""

figure图的嵌套

"""

import matplotlib.pyplot as plt

# 定义figure

fig = plt.figure()

# 定义数据

x = [1, 2, 3, 4, 5, 6, 7]

y = [1, 3, 4, 2, 5, 8, 6]

# figure的百分比, 从figure 10%的位置开始绘制, 宽高是figure的80%

left, bottom, width, height = 0.1, 0.1, 0.8, 0.8

# 获得绘制的句柄

ax1 = fig.add_axes([left, bottom, width, height])

# 绘制点(x,y)

ax1.plot(x, y, 'r')

ax1.set_xlabel('x')

ax1.set_ylabel('y')

ax1.set_title('test')

# 嵌套方法一

# figure的百分比, 从figure 10%的位置开始绘制, 宽高是figure的80%

left, bottom, width, height = 0.2, 0.6, 0.25, 0.25

# 获得绘制的句柄

ax2 = fig.add_axes([left, bottom, width, height])

# 绘制点(x,y)

ax2.plot(x, y, 'r')

ax2.set_xlabel('x')

ax2.set_ylabel('y')

ax2.set_title('part1')

# 嵌套方法二

plt.axes([bottom, left, width, height])

plt.plot(x, y, 'r')

plt.xlabel('x')

plt.ylabel('y')

plt.title('part2')

plt.show()

14- 主次坐标轴

# -*- coding: utf-8 -*-

"""

主次坐标轴

"""

import numpy as np

import matplotlib.pyplot as plt

# 定义数据

x = np.arange(0, 10, 0.1)

y1 = 0.05 * x ** 2

y2 = -1 * y1

# 定义figure

fig, ax1 = plt.subplots()

# 得到ax1的对称轴ax2

ax2 = ax1.twinx()

# 绘制图像

ax1.plot(x, y1, 'g-')

ax2.plot(x, y2, 'b--')

# 设置label

ax1.set_xlabel('X data')

ax1.set_xlabel('Y1', color = 'g')

ax2.set_xlabel('Y2', color = 'b')

plt.show()

15- 创建动画

# -*- coding: utf-8 -*-

"""

动画

"""

import numpy as np

import matplotlib.pyplot as plt

from matplotlib import animation

# 定义figure

fig, ax = plt.subplots()

# 定义数据

x = np.arange(0, 2 * np.pi, 0.01)

# line, 表示只取返回值中的第一个元素

line, = ax.plot(x, np.sin(x))

# 定义动画的更新

def update(i):

line.set_ydata(np.sin(x + i/10))

return line,

# 定义动画的初始值

def init():

line.set_ydata(np.sin(x))

return line,

# 创建动画

ani = animation.FuncAnimation(fig = fig, func = update, init_func = init, interval = 10, blit = False, frames = 200)

# 展示动画

plt.show()

# 动画保存

#我这里是保存为html文件了,打开即可完美运行

ani.save('sin.html', writer = 'imagemagick', fps = 30, dpi = 100)

python 三维绘图库_Python第三方库matplotlib(2D绘图库)入门与进阶相关推荐

  1. matplotlib是python第三方库吗_python第三方库matplotlib

    matplotlib是受MATLAB的启发构建的.MATLAB是数据绘图领域广泛使用的语言和工具.MATLAB语言是面向过程的.利用函数的调用,MATLAB中可以轻松的利用一行命令来绘制直线,然后再用 ...

  2. python 树结构三方包_python第三方库---BeautifulSoup库(搬运)

    BeautifulSoup4是爬虫必学的技能.BeautifulSoup最主要的功能是从网页抓取数据,Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码. ...

  3. python学习笔记项目_python第三方库之Django学习笔记一

    1.安装Django pip install Django 2.版本号查询 python -m django --version 3.创建项目 切换到你想创建项目的目录,执行命令:django-adm ...

  4. 霍兰德人格分析:利用Python第三方库matplotlib绘制雷达图

    美国约翰霍普金斯大学霍兰德教授认为,个人职业兴趣特性与职业之间应有一种内在的对应关系.根据兴趣的不同,人格可分为研究型(I).艺术型(A).社会型(S).企业型(E).传统型(C).现实型(R)六个维 ...

  5. python 离线下载和安装第三方库 .whl wheel 文件

    python 离线下载和安装第三方库 .whl wheel 文件 下载 .whl 文件 pip download \--only-binary=:all: \ # 对于包以及包的依赖包,都不使用二进制 ...

  6. Python 三维可视化笔记1 -- TVTK库

    Python 三维可视化笔记1 – TVTK库 Python 三维可视化系列笔记是笔者在学习黄天羽老师的<Python科学计算三维可视化>课程及笔者实践三维可视化的笔记. 课程链接: Py ...

  7. Python基础 | Anaconda环境下第三方库的安装

    文章目录 标准库和第三方库 查看第三方库 安装第三方库:以视频下载神器you-get为例 从Python的官方源安装第三方库 通过镜像网站安装第三方库 you-get库的使用 下载<资本的故事& ...

  8. Python第三方库matplotlib(2D绘图库)入门与进阶

    文章目录 @[toc] Matplotlib 一 简介: 二 相关文档: 三 入门与进阶案例 1- 简单图形绘制 2- figure的简单使用 3- 设置坐标轴 4- 设置legend图例 5- 添加 ...

  9. python之Matplotlib(2D绘图库)

    Matplotlib 绘制基础 头部引包 直线 折线 设置标签文字和线条粗细 解决标签.标题中的中文问题 一元二次方程的曲线y=x^2 正弦.余弦函数 散点图 柱状图 np.random.randin ...

最新文章

  1. IDEA设置git提交需要忽略的文件
  2. caffe的prototxt文件
  3. 上传第三方jar包到nexus
  4. OpenCV人脸检测并把图片写成avi视频
  5. android 弹窗 onpause,Android 下拉通知栏时Activity的生命周期——重新理解onPause()
  6. Server 2003 终端超过了最大允许连接数解决
  7. linux下QOS--理论篇
  8. SCI分区:JCR分区和中科院分区 的差别
  9. CodeForce Round#49 untitled (Hdu 5339)
  10. JavaSE基础——异常机制
  11. html花瓣特效代码,网页上漂浮的花瓣
  12. 访问网站提示:您未被授权查看该页恢复办法
  13. 超级小白的AOP之Springboot 日志工程
  14. 图神经网络学习过程心得总结
  15. ply补全为立方体_PLY文件格式及其解析 | 学步园
  16. win10开启最小化托盘/系统托盘
  17. 高通平台开发系列讲解(AI篇)SNPE工作流程介绍
  18. [BZOJ3653][长链剖分]谈笑风生
  19. java保证一段代码枷锁_Java堆外内存之突破JVM枷锁
  20. 批次更新失败服务器返回的信息,服务器出现大批量登录审核失败/NtLmSsp攻击

热门文章

  1. 技术人写作和写代码一样重要
  2. tez什么意思_传统数仓和大数据数仓的区别是什么?
  3. swift x输入流_Swift 中不同窗体的切换和传递数据 (segue 的用法)
  4. datetime unix php,PHP基于DateTime类解决Unix时间戳与日期互转问题【针对1970年前及2038年后时间戳】...
  5. Bash脚本教程之启动环境
  6. java 线程 Thread Runnable 实现样例
  7. 布尔表达式的语法及语义分析程序_XSS语义分析的阶段性总结(一)
  8. 微信小程序实战–集阅读与电影于一体的小程序项目(八)
  9. 结合WebSocket编写WebGL综合场景示例
  10. 在WebGL场景中进行棋盘操作的实验