matplotlib教程学习笔记

pyplot 介绍

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  1. plt.plot([1, 2, 3, 4])
  2. plt.ylabel('some numbers')
  3. plt.show()

  • 注意:pyplot的函数往往也是对象的函数
  1. fig, (ax1, ax2) = plt.subplots(1, 2)
  2. ax1.plot([1, 2, 3, 4])
  3. ax2.plot([2, 3, 4, 5])
  4. #ax1.ylabel("...") 没有这个方法。。。
  5. #fig.show()会显示non-GUI-backend而不能执行, 而ax1.show() 或者ax2.show(),没有该方法
  6. #估计得通篇看完再能窥其门径了

从上面的例子可以看出,纵坐标是我们给的数据,而横坐标,pyplot会自动从0给予编号。

  1. plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
  2. plt.show()

修饰你的图案

pyplot格式继承自matlab(我不知道)。plot的第三个可选参数是一个格式字符串,代表颜色和曲线的种类,默认为"b-"。

  1. plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') #'ro' : red circles 红色的圆
  2. plt.axis([0, 6, 0, 20]) # [xmin, xmax, ymin, ymax]
  3. plt.show()

格式字符串 [color][marker][line]

fmt = ‘[color][marker][line]’

Colors

当格式字符串只限制颜色的时候,你可以写颜色的全称,也可以用16进制来表达。

或者任意的matplotlib.colors

  1. plt.plot([1, 2, 3, 4], [1, 4, 9, 16], '#FF0000')
  2. plt.axis([0, 6, 0, 20])
  3. plt.show()

Markers

Line Styles

  1. plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'g*--') #绿色 * 虚线
  2. plt.axis([0, 6, 0, 20])
  3. plt.show()

利用关键字作图(大概是数据映射到属性吧)

  1. data = {'a': np.arange(50),
  2. 'c': np.random.randint(0, 50, 50),
  3. 'd': np.random.randn(50)}
  4. data['b'] = data['a'] + 10 * np.random.randn(50)
  5. data['d'] = np.abs(data['d']) * 100
  6. plt.scatter('a', 'b', c='c', s='d', data=data)
  7. plt.xlabel('entry a')
  8. plt.ylabel('entry b')
  9. plt.show()

传入类别

  1. names = ['group_a', 'group_b', 'group_c']
  2. values = [1, 10, 100]
  3. plt.figure(1, figsize=(9, 3)) #figsize: 长9个单位,高3个单位
  4. plt.subplot(131) #131
  5. plt.bar(names, values)
  6. plt.subplot(132)
  7. plt.scatter(names, values)
  8. plt.subplot(133)
  9. plt.plot(names, values)
  10. plt.suptitle('Categorical Plotting')
  11. plt.show()

控制线的属性

线有许多属性,比如线的宽度,虚线的形式等等。

我们有很多方法来设置线的属性:

  1. plt.plot(x, y, linewidth=2.0)

使用line2D对象的setter方法也可以完成。

  1. x1 = np.array([1, 2, 3, 4])
  2. y1 = x1 ** 2
  3. x2 = np.array([4, 3, 2, 1])
  4. y2 = np.sin(x2)
  5. line1, line2 = plt.plot(x1, y1, x2, y2)
  6. line1.set_antialiased(False) #关闭抗锯齿
  7. line2.set_linewidth(5.0)
  8. plt.show()

使用setp()指令同样能够办到,这玩意儿还会返回图片的各种属性。

  1. x1 = np.array([1, 2, 3, 4])
  2. y1 = x1 ** 2
  3. x2 = np.array([4, 3, 2, 1])
  4. y2 = np.sin(x2)
  5. lines = plt.plot(x1, y1, x2, y2)
  6. plt.setp(lines, color='r', linewidth=2.0)

Line2D的属性

  1. pro1 = {
  2. 'alpha':0.2,
  3. 'animated':True, #动画?啥效果?
  4. 'antialiased':True,#抗锯齿 默认为True
  5. 'color': 'red',
  6. 'dash_capstyle': 'butt', #不知道干啥的 包裹起来?
  7. 'dash_joinstyle': 'miter', #不知道干啥的
  8. 'label': "会出现吗?",
  9. 'linestyle': 'steps',
  10. #'lod': True 为啥没这属性
  11. 'marker': '+',
  12. 'markeredgecolor': 'red', #断点的颜色?
  13. 'markeredgewidth': 2.0, #断点的大小
  14. 'markerfacecolor': 'yellow',
  15. 'markersize': 6.0 #这个是那个断点的大小,可是是什么压制了它的洪荒之力
  16. }
  17. pro2 = {
  18. 'alpha':0.8,
  19. 'animated':False,
  20. 'aa':False,
  21. 'c': '#00FF00',
  22. 'linestyle': '--',
  23. 'marker': '1',
  24. 'mec': 'blue',
  25. 'mew': 3.0,
  26. 'mfc': 'yellow', #啥意思啊,嵌了一层黄色
  27. 'ms': 2.0
  28. }
  29. x1 = np.arange(20)
  30. y1 = x1
  31. x2 = np.linspace(0, 20, 50)
  32. y2 = np.sin(x2)
  33. line1, line2 = plt.plot(x1, y1, x2, y2)
  34. # use keyword args
  35. plt.setp(line1, **pro1)
  36. plt.setp(line2, **pro2)
  37. plt.show()

操作多figures和axes

matlab和pyplot都有当前figure,axes的概念,所有画图操作都会应用到当前的axes上。函数gca()会返回当前的axes对象,而gcf()会返回当前figure对象。

  1. def f(t):
  2. return np.exp(-t) * np.cos(2*np.pi*t)
  3. t1 = np.arange(0.0, 5.0, 0.1)
  4. t2 = np.arange(0.0, 5.0, 0.02)
  5. plt.figure(1)
  6. plt.subplot(211)
  7. plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
  8. plt.subplot(212)
  9. plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
  10. plt.show()

subplot(mnk)

m: numrows

n: numcols

k: plot_numer [1-m*n]

就相当于把一块画布割成m行n列,即有mn块小区域,k就是我们要子图所放的区域的标识,从1到mn。而且,从下面的例子中可以看出,位置是从上到下,从左往右标号的。

  1. def f(t):
  2. return np.exp(-t) * np.cos(2*np.pi*t)
  3. t1 = np.arange(0.0, 5.0, 0.1)
  4. plt.figure(1)
  5. plt.subplot(221)
  6. plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
  7. plt.subplot(222)
  8. plt.plot(t1, f(t1), 'ro', t2, f(t2), 'k')
  9. plt.subplot(223)
  10. plt.plot(t1, f(t1), 'go', t2, f(t2), 'k')
  11. plt.subplot(224)
  12. plt.plot(t1, f(t1), 'yo', t2, f(t2), 'k')
  13. plt.show()

clf()清空当前figure, cla()情况当前axes.

另外,figure所占内存,只用当调用close()的时候才会完全释放。

加入Text

text() :可将文本加入至任意位置

xlabel(), ylabel(), title() :加入至固定位置

  1. mu, sigma = 100, 15
  2. x = mu + sigma * np.random.randn(10000)
  3. # the histogram of the data
  4. n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
  5. plt.xlabel('Smarts')
  6. plt.ylabel('Probability')
  7. plt.title('Histogram of IQ')
  8. plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
  9. #r表示原始字符串,否则得这么写plt.text(60, .025, '$\\mu=100,\ \\sigma=15$')
  10. plt.axis([40, 160, 0, 0.03])
  11. plt.grid(True)
  12. plt.show()

Annotating text

annoate()

  1. ax = plt.subplot(111)
  2. t = np.arange(0.0, 5.0, 0.01)
  3. s = np.cos(2*np.pi*t)
  4. line, = plt.plot(t, s, lw=2)
  5. plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
  6. arrowprops=dict(facecolor='black', shrink=0.05),
  7. )
  8. plt.ylim(-2, 2)
  9. plt.show()

非线性axes

pyplot提供非线性标度,如对数化等等。(纵坐标好像还是原来的y,只是图像变了)

  1. from matplotlib.ticker import NullFormatter # useful for `logit` scale
  2. # Fixing random state for reproducibility
  3. np.random.seed(19680801)
  4. # make up some data in the interval ]0, 1[
  5. y = np.random.normal(loc=0.5, scale=0.4, size=1000)
  6. y = y[(y > 0) & (y < 1)]
  7. y.sort()
  8. x = np.arange(len(y))
  9. # plot with various axes scales
  10. plt.figure(1)
  11. # linear
  12. plt.subplot(221)
  13. plt.plot(x, y)
  14. plt.yscale('linear')
  15. plt.title('linear')
  16. plt.grid(True)
  17. # log
  18. plt.subplot(222)
  19. plt.plot(x, y)
  20. plt.yscale('log')
  21. plt.title('log')
  22. plt.grid(True)
  23. # symmetric log
  24. plt.subplot(223)
  25. plt.plot(x, y - y.mean())
  26. plt.yscale('symlog', linthreshy=0.01)
  27. plt.title('symlog')
  28. plt.grid(True)
  29. # logit
  30. plt.subplot(224)
  31. plt.plot(x, y)
  32. plt.yscale('logit')
  33. plt.title('logit')
  34. plt.grid(True)
  35. # Format the minor tick labels of the y-axis into empty strings with
  36. # `NullFormatter`, to avoid cumbering the axis with too many labels.
  37. plt.gca().yaxis.set_minor_formatter(NullFormatter())
  38. # Adjust the subplot layout, because the logit one may take more space
  39. # than usual, due to y-tick labels like "1 - 10^{-3}"
  40. plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
  41. wspace=0.35)
  42. plt.show()

matplotlib 入门之Pyplot tutorial的更多相关文章

  1. matplotlib 入门之Image tutorial

    文章目录 载入图像为ndarray 显示图像 调取各个维度 利用cmp 获得像素点的RGB的统计 通过clim来限定rgb 标度在下方 插值,马赛克,虚化 matplotlib教程学习笔记 impor ...

  2. 绘图神器-matplotlib入门

    这次,让我们使用一个非常有名且十分有趣的玩意儿来完成今天的任务,它就是jupyter. 一.安装jupyter matplotlib入门之前,先安装好jupyter.这里只提供最为方便快捷的安装方式: ...

  3. Python 绘图库Matplotlib入门教程

    0 简单介绍 Matplotlib是一个Python语言的2D绘图库,它支持各种平台,并且功能强大,能够轻易绘制出各种专业的图像. 1 安装 pip install matplotlib 2 入门代码 ...

  4. Matplotlib 入门

    章节 Matplotlib 安装 Matplotlib 入门 Matplotlib 基本概念 Matplotlib 图形绘制 Matplotlib 多个图形 Matplotlib 其他类型图形 Mat ...

  5. Sahi (1) —— 快速入门(101 Tutorial)

    Sahi (1) -- 快速入门(101 Tutorial) jvm版本: 1.8.0_65 sahi版本: Sahi Pro 6.1.0 参考来源: Sahi官网 Sahi Quick Tutori ...

  6. python数据可视化——matplotlib 用户手册入门:pyplot 画图

    参考matplotlib官方指南: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-intro ...

  7. matplotlib 入门之Sample plots in Matplotlib

    文章目录 Line Plot One figure, a set of subplots Image 展示图片 展示二元正态分布 A sample image Interpolating images ...

  8. Pyplot tutorial,Pyplot官方教程自翻译

      matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB ...

  9. IPython绘图和可视化---matplotlib 入门

    最近总是需要用matplotlib绘制一些图,由于是新手,所以总是需要去翻书来找怎么用,即使刚用过的,也总是忘.所以,想写一个入门的教程,一方面帮助我自己熟悉这些函数,另一方面有比我还小白的新手可以借 ...

随机推荐

  1. mssql sqlserver 模拟for循环的写法

    转自:http://www.maomao365.com/?p=6567 摘要: 下文讲述sql脚本模拟for循环的写法,如下所示: /* for样例 for('初始值','条件','执行后自增') 通 ...

  2. javaweb分页查询实现

    Javaweb分页技术实现 分页技术就是通过SQL语句(如下)来获取数据,具体实现看下面代码 //分页查询语句 select * from 表名 where limit page , count; 和 ...

  3. C#判断文件编码——常用字法

    使用中文写文章,当篇幅超过一定程度,必然会使用到诸如:“的”.“你”.“我”这样的常用字.本类思想便是提取中文最常用的一百个字,使用中文世界常用编码(主要有GBK.GB2312.GB18030.UTF ...

  4. Process 0:0:0 (0x1ffc) Worker 0x00000001E580A1A0 appears to be non-yielding on Scheduler 3. Thread creation time: 13153975602106.

    现场报错如下: Process 0:0:0 (0x1ffc) Worker 0x00000001E580A1A0 appears to be non-yielding on Scheduler 3. ...

  5. .net的mvc的fw版本为4.5发布到阿里云【云虚拟主机】上.

    注意:云虚拟主机和云服务器(ECS)不是同一个产品,请注意分别. 云服务器ECS: 云虚拟主机: 我用的是云虚拟主机也是第二个,版本是window server  声明:默认,已经把域名[已备案]绑定 ...

  6. 【PAT】B1008 数组元素循环右移问题

    猥琐方法 直接分成两部分输出数组元素,注意空格的问题 #include<stdio.h> int arr[101]; void Priarr(int a,int b){ if(a<= ...

  7. C# -- 正则表达式匹配字符之含义

    C#正则表达式匹配字符之含义 1.正则表达式的作用:用来描述字符串的特征. 2.各个匹配字符的含义: .   :表示除\n以外的单个字符 [ ]  :表示在字符数组[]中罗列出来的字符任意取单个 | ...

  8. Python语法基础-函数,类以及调试处理

    [TOC] 1. 函数的定义 python中函数有两种: python自带的函数 用户定义函数 返回多个值 原来返回值是一个tuple!但是,在语法上,返回一个tuple可以省略括号,而多个变量可以同 ...

  9. ABAP 7.50 新特性 – Open SQL中的宿主表达式和其它表达式

    在长期的停滞后,Open SQL的发展终于从沉睡中醒来.从ABAP 7.40开始,SAP推进了某些关键的改变,以尽可能地包含SQL92中的特性,并提供与ABAP CDS中的DDL里面的SELECT一样 ...

  10. MySQL初识

    1.MySQL版本 社区版:免费的,功能够用. 商业版:更能更加强大,更加稳定,但是收费的. 2.每个版本都分四个版本发布 Alpha版本:一般只在开发公司内部使用,不对外公开,测试.自我检查版本: ...