最近自己经常遇到matplotlib的OO API和pyplot包混乱不分的情况,所以抽时间好好把matplotlib的文档读了一下,下面是大概的翻译和总结。很多基础的东西还是要系统地掌握牢固哇~~另外一篇翻译是

曲奇:matplotlib中文入门文档(user guide)​zhuanlan.zhihu.com

matplotlib.pyplot是一个函数的集合,每一个pyplot下面的函数都在figure上做一些动作。

pyplot的动作默认是在当前的Axes上。

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

如果plot的参数是一个单独的list或array,matplotlib认为它是y值,自动生成x轴从0开始。等价于plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

制定plot的颜色和线型

对于每一个x-y对,都有一个可选的参数,“颜色+线型”的字符串

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

根据这个文档可以查看完整的线型和format: plot

axis函数则可以输入[xmin, xmax, ymin, ymax],和其他控制axis的函数。

plot函数可以同时传入多条线和参数

import numpy as np# evenly sampled time at 200ms intervals
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()

根据keyword参数plot

可以传入字典或pd.DataFrame,np.recarray。matplotlib允许一个data参数。

然后用keyword指定x和y是哪些。

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)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

categorical variables

x轴可以是类别型参数

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. 使用keyword
    plt.plot(x, y, linewidth=2.0)
  2. 使用Line2D实例的setter方法,plot函数会返回一个Line2D对象。比如line1, line2 = plot(x1, y1, x2, y2)
    line, = plt.plot(x, y, '-')
    line.set_antialiased(False) # turn off antialiasing
  3. 使用step函数,它可以为一组对象或单个对象设置参数。参数的格式可以是keyword arguments或string-value对
    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的参数列表

也可以通过调用step函数,传入line或lines来获取可以设置的属性

In [69]: lines = plt.plot([1, 2, 3])In [70]: plt.setp(lines)alpha: floatanimated: [True | False]antialiased or aa: [True | False]...snip

多figures和多Axes

pyplot是在当前figure和当前axes上工作的,通过gca可以拿到当前axes(是一个 matplotlib.axes.Axes实例),通过gcf 可以拿到当前figure实例(matplotlib.figure.Figure实例)。

以下是一个创建两个subplot的实例。这里的figure函数可以不用调用的,默认会创建figure(1)。

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()
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

如果不显式调用subplot,默认是创建一个subplot(111),如果不手动指定任何axes。subplot指定numrows,numcols,plotnumber。subplot(211)等价于subplot(2,1,1)

能够手动地任意摆放axes,给axes函数传入位置[left, bottom, width, height]

# Creating a new full window axes
plt.axes()# Creating a new axes with specified dimensions and some kwargs
plt.axes((left, bottom, width, height), facecolor='w')

可以创建多个figure,只要在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

能够通过clf()函数清除当前figure或通过cla()函数清除当前axes。当图片被显式地关闭时(在python shell模式下),内存空间才会释放。调用了show()之后,如果关闭了图片,原先的figure和axes即释放。

图片上所有文本text信息

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$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

所有的text函数都会返回一个matplotlib.text.Text 实例,这个实例能够用于step的参数,并对实例设置属性。

数学函数

plt.title(r'$sigma_i=15$')

注解Annotating

需要指定被注解的位置xy(也就是箭头指向的位置)和文本位置xytext

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()

对数和其他非线性轴

改变一个轴的scale

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)
# Adjust the subplot layout, because the logit one may take more space
# 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()

参考

https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py

matplotlib.pyplot_Matplotlib Pyplot教程相关推荐

  1. matplotlib之pyplot教程

    文章目录 1. pyplot介绍 2. 使用关键字字符串绘图 3. 使用分类变量绘图 4. 线条属性控制 5. 使用多个图形和坐标轴 6. 图中添加文本 使用数学表达式 使用注释文本 7. 对数轴和其 ...

  2. python中的matplotlib.pyplot_Python matplotlib简介 Pyplot教程

    matplotlib.pyplot是一些命令行风格函数的集合,使matplotlib以类似于MATLAB的方式工作.每个pyplot函数对一幅图片(figure)做一些改动:比如创建新图片,在图片创建 ...

  3. python模块matplotlib.pyplot用法_Python matplotlib简介 Pyplot教程

    matplotlib.pyplot是一些命令行风格函数的集合,使matplotlib以类似于MATLAB的方式工作.每个pyplot函数对一幅图片(figure)做一些改动:比如创建新图片,在图片创建 ...

  4. Matplotlib 中文用户指南 3.1 pyplot 教程

    pyplot 教程 原文:Pyplot tutorial 译者:飞龙 协议:CC BY-NC-SA 4.0 matplotlib.pyplot是一个命令风格函数的集合,使matplotlib的机制更像 ...

  5. matplotlib: Pyplot 教程

    原文:https://matplotlib.org/stable/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory- ...

  6. python模块(5)-Matplotlib 简易使用教程

    Matplotlib简易使用教程 0.matplotlib的安装 1.导入相关库 2.画布初始化 2.1 隐式创建 2.2 显示创建 2.3 设置画布大小 2.4 plt.figure()常用参数 3 ...

  7. 【莫烦Python】Matplotlib Python画图教程

    目录 前言 1.基本使用 1.1 基本用法 1.2 figure图像 1.3 设置坐标轴1 1.4 设置坐标轴2 1.5 Legend图例 1.6 Annotation标注 1.7 tick能见度 2 ...

  8. pyplot绘制图片_使用matplotlib的pyplot模块绘图的实现示例

    1. 绘制简单图形 使用 matplotlib 的pyplot模块绘制图形.看一个 绘制sin函数曲线的例子. import matplotlib.pyplot as plt import numpy ...

  9. Python数据分析【1】:matplotlib库详细教程

    Python数据分析:matplotlib库详细教程 一.基本介绍 1. 数据分析 2. 环境安装 二.matplotlib 1. 基本介绍 2. 基本要点 3. 散点图/直方图/柱状图 4. 画图工 ...

最新文章

  1. 如何在Mac上的IntelliJ IDEA中增加IDE内存限制?
  2. PyObject_CallMethod self问题
  3. 杂项:E-Learning
  4. Oracle中分区表中表空间属性
  5. dw怎么修改html框架的宽度,Dreamweaver (dw)cs6中div标签宽度和高度设置方法
  6. 内核中的UDP socket流程(1)
  7. 让孩子从小自信的28个方法
  8. dump文件_零基础编程——Python文件、JSON数据存储
  9. mysqludf_json将关系数据以JSON编码
  10. 傅里叶热传导定律【Fourier's Law of Heat Conduction】
  11. android静态库动态库,Android 动态库和静态库
  12. win10修改ip或dns弹出“出现了一个意外”对话框解决办法
  13. js存储数据cookie,localhost,sessionstorage
  14. 小米5s Plus安装类原生系统
  15. 拿起手术刀 深入剖解路由器的“心脏”技术
  16. android ndk如何安装,android NDK安装
  17. 什么是网络环路问题?
  18. matlab 复数函数拟合,Matlab中实验数据【复数】的曲线拟合
  19. 磁盘存储链式的B树与B+树(上课笔记)
  20. PPT中如何找到字母上面带尖/冒的符号

热门文章

  1. c++字符串大小比较可以用来干什么?
  2. Gin的路由类型:GET POST PUT DELETE
  3. Docker安装部署MongoDB及MySql和MongoDB的语法对比
  4. Scala 字符串详解
  5. Ansible roles角色详解
  6. linux deepin/ubuntu 搭nginx文件服务器配置
  7. Sublime Text 3 快捷键总结
  8. 【代码】使用ReentrantLock还可以调用lockInterruptibly方法,可以对线程interrupt方法做出响应
  9. Scala 键盘录入对象StdIn/特质/伴生对象
  10. spring cloud常用组件介绍