Pyplot tutorial

对pyplot 接口的介绍

简介

matplotlib.pyplot 是一堆函数的集成,让matplotlib 像MATLAB 一样使用。创建画布,画线,装饰啥的。

但是 pyplot API 没有面向对象的API 灵活。

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])      # 生成一个可视化的图是非常容易的
plt.ylabel('some data')
plt.show()# 注意一下坐标轴,当只传入一个列表或数组,matplotlib就认为这是y 值得序列,然后自动生成x 的值。
# 生成的x 的值是从0开始的,所以 y 1-4 x 0-3
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

格式化绘图

除了 x,y 两个参数,还有格式化字符串这个参数,来表示颜色和绘制的线的种类。默认是 ‘b-’ ,蓝色的实线。更多格式,,这些函数的参数也太多了。。。

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')    # 红点
plt.axis([0, 6, 0, 20])    # 这个函数指定了两个坐标的可视化范围
plt.show()import numpy as np
t = np.arange(0., 5., 0.2)    # 传入列表再内部也会转换成数组。# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')    # 不同格式再一个函数里画
plt.show()

# 用关键字绘图
data = {'a': np.arange(50),'c': np.random.randint(0, 50, 50),'d': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100plt.scatter('a', 'b', c='c', s='d', data=data)   # 指定了data 这个参数
plt.xlabel('entry a')              # 就可以使用相关联的字符串
plt.ylabel('entry b')         # c 颜色, s 标记点的大小
plt.show()

用分类数据绘图

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]plt.figure(figsize=(9, 3))plt.subplot(131)
plt.bar(names, values)    # 条形图
plt.subplot(132)
plt.scatter(names, values)   # 散点图
plt.subplot(133)
plt.plot(names, values)     # 折线图
plt.suptitle('Categorical Plotting')
plt.show()

控制线的属性

宽度,样式,抗锯齿等,设置方法:

  1. plt.plot(x,y, linewidth = 2.0) 通过关键字参数

  2. line, = plt.plot(x, y, '-'); line.set_antialiased(False) # turn off 抗锯齿 通过Line2D 对象的set 方法,plot 返回的是 Line2D 对象的列表。

  3. setp 方法

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

一下就是可用的 Line2D 属性:

  1. Property Value Type
    alpha float
    animated [True | False]
    antialiased or aa [True | False]
    clip_box a matplotlib.transform.Bbox instance
    clip_on [True | False]
    clip_path a Path instance and a Transform instance, a Patch
    color or c any matplotlib color
    contains the hit testing function
    dash_capstyle ['butt' | 'round' | 'projecting']
    dash_joinstyle ['miter' | 'round' | 'bevel']
    dashes sequence of on/off ink in points
    data (np.array xdata, np.array ydata)
    figure a matplotlib.figure.Figure instance
    label any string
    linestyle or ls [ '-' | '--' | '-.' | ':' | 'steps' | …]
    linewidth or lw float value in points
    marker [ '+' | ',' | '.' | '1' | '2' | '3' | '4' ]
    markeredgecolor or mec any matplotlib color
    markeredgewidth or mew float value in points
    markerfacecolor or mfc any matplotlib color
    markersize or ms float
    markevery [ None | integer | (startind, stride) ]
    picker used in interactive line selection
    pickradius the line pick selection radius
    solid_capstyle ['butt' | 'round' | 'projecting']
    solid_joinstyle ['miter'| 'round' | 'bevel']
    transform a matplotlib.transforms.Transform instance
    visible [True | False]
    xdata np.array
    ydata np.array
    zorder any number
lines = plt.plot([1, 2, 3])
plt.step(lines)     # 获取可设置的线的属性列表(不是这个对象的取值)。。蛮方便的啊

使用多个图形和轴

绘图中,所有的函数都是i针对当前的图和轴,可以使用 Axes.gca 得到当前的轴, gcf 得到当前的图,一般不用管,交给后台就行

def f(t):return np.exp(-t) * np.cos(2*np.pi*t)t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)plt.figure()    # 也可以不用这个,因为figure(1) 会默认创建。
plt.subplot(211)     # 选择绘制的子图,两行一列第一个
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')plt.subplot(212)   # 也可以写成( 2, 1, 2)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()# 也可以创建多个 figure
import matplotlib.pyplot as plt
plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by defaultplt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

可以使用 pyplot.clf() or cla() 来清除当前的 figure 和 axes。如果你制作了大量的图形,注意再图形通过 close() 关闭前,其内存是不会释放的 matplotlib.pyplot.close(fig=None)

文本

text 可用添加再任意位置,xlabel ylabel title 可用给指定位置增加文本

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')   # 支持 TeX 方程表达式
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()# 这些文本函数都是 text.Text 实例,可用定义属性
t = plt.xlabel('my data', fontsize=14, color='red')  # or setp()

标记文本

使用 annotate 方法来标注文本,有两个位置 标志位置 (x,y) 和文本位置 (xtext, ytext)。

ax = plt.subplot(111)t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05),   # 箭头格式)plt.ylim(-2, 2)
plt.show()

对数和其他非线性轴

不仅支持线性轴刻度,也支持对数 和 log 的刻度,如果数据跨越很多数量级,就可以改变轴的比率。plt.xscale(‘log’)

# Fixing random state for reproducibility
np.random.seed(19680801)# make up some data in the open interval (0, 1)
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))# plot with various axes scales
plt.figure()# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthresh=0.01)
plt.title('symlog')
plt.grid(True)# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# 调整子图布局,因为logit可能会占用更多空间
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,wspace=0.35)plt.show()

matplotlib 文档:Pyplot tutorial相关推荐

  1. 书评 | 如何让开发中的各种文档变活?《活文档》阅读总结

    题图 | © Yunshan Xia 几年前在 O'Reilly 看到一本叫 Living Documentation 的书,可惜当时没读完. 最近图灵出版了该书的中文翻译版<活文档:与代码共同 ...

  2. 项目中的难点怎么克服_克服大型项目中的文档挑战

    项目中的难点怎么克服 鉴于最近熊猫( Pandas) ,NumPy和Matplotlib等开放源数据科学项目的普及Swift增长,人们对文档的兴趣日益浓厚 ,这不足为奇. 为了帮助您了解所面临的问题, ...

  3. python教程-数据分析-matplotlib绘制折线图1(改变图片大小,保存图片,改变坐标的间距,显示中文,快捷键出对应文档)

    matplotlib学习笔记: `matplotlib`之缘起 导入包 绘制简单的折线图 改变图片大小 保存图片 改变坐标轴的间距 调整图片的密集程度 学到这,要来一题练练手了! 在matplotli ...

  4. Rasa 文档 中英文翻译版本 3 - Tutorial: Building Assistants

    Rasa 文档 中英文翻译版本 3 - Tutorial: Building Assistants https://rasa.com/docs/rasa/user-guide/building-ass ...

  5. Python Tutorial中英双语对照文档5

    Python Tutorial中英双语对照文档4 CHAPTER THIRTEEN WHAT NOW? 现在咧? Reading this tutorial has probably reinforc ...

  6. Python Tutorial中英双语对照文档1

    本文根据官方文档 http://www.pythondoc.com/pythontutorial3/ 和 中文文档 http://www.pythondoc.com/pythontutorial3/ ...

  7. Python Tutorial中英双语对照文档2

    接 Python Tutorial中英双语对照文档1 CHAPTER SIX MODULES 模块 If you quit from the Python interpreter and enter ...

  8. Python Tutorial中英双语对照文档3

    接 Python Tutorial中英双语对照文档2 CHAPTER NINE CLASSES 类 Classes provide a means of bundling data and funct ...

  9. excel 文档管理服务器,Excel Server Tutorial

    在企事业单位的实际业务中所需要使用的信息,除了数据之外,还包括文档.文档是各种类别和格式的,它们可能是Word文件,如企业的规章制度:可能是AutoCAD文件,如产品设计图纸:也可能是视频.音频文件, ...

最新文章

  1. 【转载】快速升职加薪的10个方法
  2. Executor框架的详解(转载)
  3. 贪婪算法、递归计算、动态规划背包问题
  4. 网页制作中最有用的免费Ajax和JavaScript代码库
  5. auto-sklearn手册
  6. 无线数传电台工业控制的应用
  7. 【离散数学】浅析小项与主析取范式和大项与主合取范式
  8. 再见了亲爱的学生们,再见了敬爱的同事们,再见了信狮
  9. vue导出数据为Excel文件
  10. 给定一个邻接矩阵,求可达矩阵及强连通、单向连通、弱连通、不连通的判断
  11. 计算机 统计学考研,统计学考研科目有哪些
  12. 华三基础命令(单臂,超级vlan,远程,聚合)
  13. cocos2d-x游戏开发 《坠入蔚蓝》
  14. WIN10 如何隐藏桌面图标
  15. Gdrive 使用教程
  16. 摄像头采集图像本地HDMI输出延迟测试
  17. 0-c语言入门这一篇就够了-学习笔记(一万字)
  18. 第十二周 静态 +友元 + 动态 + 继承 + 多文件
  19. javaAPI文档中文版(JDK11在线版)无需下载、直接打开
  20. K8S中的容器网络概述(编写中)

热门文章

  1. 【C语言经典100例】 -- 28 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后
  2. fread函数详解 函数原型
  3. 东方国信基于kubernetes构建容器云平台的实践和思考
  4. 什么是CRUD? 数据库(含CRUD)的操作
  5. 深度学习之格式转换笔记(三):keras(.hdf5)模型转TensorFlow(.pb) 转TensorRT(.uff)格式
  6. 基于51单片机的LED呼吸灯设计(定时器)
  7. Win10+vs2017跑yolov3
  8. 思创易控cetron-Cetron Wi-Fi 6 AP 荣获2020年度创新产品•鼎智奖
  9. VMware的下载和安装(最详细)
  10. 西游记笔记与想法(4)