Python中基础使用及Numpy、Scipy、Matplotlib 使用教程

本文主要根据 斯坦福CS231n课程的Python 教程进行整理,原文地址为http://cs231n.github.io/python-numpy-tutorial/,官方Python指南网址https://www.python.org/doc/

Python是本身是一个通用的编程语言,但其具有一些库(numpy,scipy,matplotlib)用于科学运算,原文的Python的版本是3.5。

本文先进行Python的基本介绍(数据、容器、函数、类)然后再介绍Numpy库、SciPy库以及MatPlotlib库的常用方法。

Python基本数据类型

  1. 整型 int ,浮点型 float (注:Python没有i++这种语句,乘方用x**i)
  2. 布尔型 booleans (注:Python 使用 and 、or、not替代C语言的&&、||、!;t!=f表示t和f的异或)
  3. 字符串型 strings (注:Python中字符串可以用单引号或双引号表示,一些常用的函数如大小写、去除空格、字符串替换、空格位置调整等,去掉空格s.strip()字符串替换s.replace('l','ell')具体使用什么函数可以现查)

Python容器

  • 列表 list,与数组相同但是可变大小(注:下标从0开始算,与maltab从1开始算不同)
  1. xs = [3, 1, 2] # Create a list
  2. print(xs, xs[2]) # Prints "[3, 1, 2] 2" 注意小标从0开始
  3. print(xs[-1]) # 负数下标从后往前数; prints "2"
  4. xs[2] = 'foo' # 列表的元素可以类型不同
  5. print(xs) # Prints "[3, 1, 'foo']"
  6. xs.append('bar') # 增加元素
  7. print(xs) # Prints "[3, 1, 'foo', 'bar']"
  8. x = xs.pop() # 删除最后一个元素
  9. print(x, xs) # Prints "bar [3, 1, 'foo']"

切片:list使用中的一个重要方法(注:切片的下标左边界包含,右边界不包含,与matlab两边界都包含不同)

  1. nums = list(range(5)) # 利用list()函数生成列表
  2. print(nums) # Prints "[0, 1, 2, 3, 4]"
  3. print(nums[2:4]) # 切片下标2到(4-1); prints "[2, 3]"
  4. print(nums[2:]) # 切片下标2到最后; prints "[2, 3, 4]"
  5. print(nums[:2]) # 切片开始到下标(2-1); prints "[0, 1]"
  6. print(nums[:]) # 切片全部; prints "[0, 1, 2, 3, 4]"
  7. print(nums[:-1]) # 切片开始到(-1-1); prints "[0, 1, 2, 3]"
  8. nums[2:4] = [8, 9] # 将下标2,3的值替换成8,9
  9. print(nums) # Prints "[0, 1, 8, 9, 4]"

 列表元素循环(与matlab相同)

  1. animals = ['cat', 'dog', 'monkey']
  2. for animal in animals:
  3. print(animal)
  4. # 三行分别打印 cat dog monkey

也可以利用内建函数enumerate(Lists)取得下标(从0开始)和元素

  1. animals = ['cat', 'dog', 'monkey']
  2. for idx, animal in enumerate(animals):
  3. print('#%d: %s' % (idx + 1, animal))
  4. # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line

列表解析:一种生成新的列表的方式,举两个例子

  1. nums = [0, 1, 2, 3, 4]
  2. squares = [x ** 2 for x in nums]
  3. print(squares) # Prints [0, 1, 4, 9, 16]
  1. nums = [0, 1, 2, 3, 4]
  2. even_squares = [x ** 2 for x in nums if x % 2 == 0]
  3. print(even_squares) # Prints "[0, 4, 16]"
  • 字典 dictionaries,存储键值对(key,value)
  1. d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data
  2. print(d['cat']) # Get an entry from a dictionary; prints "cute"
  3. print('cat' in d) # Check if a dictionary has a given key; prints "True"
  4. d['fish'] = 'wet' # Set an entry in a dictionary
  5. print(d['fish']) # Prints "wet"
  6. # print(d['monkey']) # KeyError: 'monkey' not a key of d
  7. print(d.get('monkey', 'N/A')) # Get an element with a default; prints "N/A"
  8. print(d.get('fish', 'N/A')) # Get an element with a default; prints "wet"
  9. del d['fish'] # Remove an element from a dictionary
  10. print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"

字典循环

  1. d = {'person': 2, 'cat': 4, 'spider': 8}
  2. for animal in d:
  3. legs = d[animal]
  4. print('A %s has %d legs' % (animal, legs))
  5. # Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"

也可以利用内建函数d.items()取得键和值

  1. d = {'person': 2, 'cat': 4, 'spider': 8}
  2. for animal, legs in d.items():
  3. print('A %s has %d legs' % (animal, legs))
  4. # Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"

字典解析,利用表达式生成字典

  1. nums = [0, 1, 2, 3, 4]
  2. even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
  3. print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"
  • 集合sets(注:集合中元素无序且不重复)
  1. animals = {'cat', 'dog'}
  2. print('cat' in animals) # Check if an element is in a set; prints "True"
  3. print('fish' in animals) # prints "False"
  4. animals.add('fish') # Add an element to a set
  5. print('fish' in animals) # Prints "True"
  6. print(len(animals)) # Number of elements in a set; prints "3"
  7. animals.add('cat') # Adding an element that is already in the set does nothing
  8. print(len(animals)) # Prints "3"
  9. animals.remove('cat') # Remove an element from a set
  10. print(len(animals)) # Prints "2"

集合循环,与数组循环语法相同,但是注意其无序性。

  1. animals = {'cat', 'dog', 'fish'}
  2. for idx, animal in enumerate(animals):
  3. print('#%d: %s' % (idx + 1, animal))
  4. # Prints "#1: fish", "#2: dog", "#3: cat"

集合解析:利用解析表达式生成集合

  1. from math import sqrt
  2. nums = {int(sqrt(x)) for x in range(30)}
  3. print(nums) # Prints "{0, 1, 2, 3, 4, 5}"
  • 元组 tuple,与数组类似,但其实不可变的列表,因此可以作为字典dictionary中的键key或集合set的元素(注:列表由于可变无法成为dictionary的key和set的元素)
  1. d = {(x, x + 1): x for x in range(10)} # Create a dictionary with tuple keys
  2. t = (5, 6) # Create a tuple
  3. print(type(t)) # Prints "<class 'tuple'>"
  4. print(d[t]) # Prints "5"
  5. print(d[(1, 2)]) # Prints "1"

Python函数

利用关键字def,返回使用return

  1. def sign(x):
  2. if x > 0:
  3. return 'positive'
  4. elif x < 0:
  5. return 'negative'
  6. else:
  7. return 'zero'
  8. for x in [-1, 0, 1]:
  9. print(sign(x))
  10. # Prints "negative", "zero", "positive"

参数可以使可选的的例子

  1. def hello(name, loud=False):
  2. if loud:
  3. print('HELLO, %s!' % name.upper())
  4. else:
  5. print('Hello, %s' % name)
  6. hello('Bob') # Prints "Hello, Bob"
  7. hello('Fred', loud=True) # Prints "HELLO, FRED!"

Python类

定义类的Python语法的格式如下

  1. class Greeter(object):
  2. # Constructor
  3. def __init__(self, name):
  4. self.name = name # Create an instance variable
  5. # Instance method
  6. def greet(self, loud=False):
  7. if loud:
  8. print('HELLO, %s!' % self.name.upper())
  9. else:
  10. print('Hello, %s' % self.name)
  11. g = Greeter('Fred') # 构造Greeter类的实例
  12. g.greet() # 调用类函数;prints "Hello, Fred"
  13. g.greet(loud=True) # 调用类函数; prints "HELLO, FRED!"

Numpy

numpy库用于python科学计算,与matlab有相似之处,其核心是对数组arrays的操作。

数组arrays

数组array是numpy提供的容器,能够通过列表list生成,利用方括号取元素(注:下标从0开始)

  1. import numpy as np
  2. a = np.array([1, 2, 3]) # Create a rank 1 array
  3. print(type(a)) # Prints "<class 'numpy.ndarray'>"
  4. print(a.shape) # Prints "(3,)"
  5. print(a[0], a[1], a[2]) # Prints "1 2 3"
  6. a[0] = 5 # Change an element of the array
  7. print(a) # Prints "[5, 2, 3]"
  8. b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
  9. print(b.shape) # Prints "(2, 3)"
  10. print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"

与matlab类似,numpy提供了一些生成特殊数组的函数

  1. import numpy as np
  2. a = np.zeros((2,2)) # Create an array of all zeros
  3. print(a) # Prints "[[ 0. 0.]
  4. # [ 0. 0.]]"
  5. b = np.ones((1,2)) # Create an array of all ones
  6. print(b) # Prints "[[ 1. 1.]]"
  7. c = np.full((2,2), 7) # Create a constant array
  8. print(c) # Prints "[[ 7. 7.]
  9. # [ 7. 7.]]"
  10. d = np.eye(2) # Create a 2x2 identity matrix
  11. print(d) # Prints "[[ 1. 0.]
  12. # [ 0. 1.]]"
  13. e = np.random.random((2,2)) # Create an array filled with random values
  14. print(e) # Might print "[[ 0.91940167 0.08143941]
  15. # [ 0.68744134 0.87236687]]"

数组切片,利用方括号内的逗号和冒号对每个维度进行索引,基本与matlab相同(注:左包括右不包括)

  1. import numpy as np
  2. # Create the following rank 2 array with shape (3, 4)
  3. # [[ 1 2 3 4]
  4. # [ 5 6 7 8]
  5. # [ 9 10 11 12]]
  6. a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
  7. # Use slicing to pull out the subarray consisting of the first 2 rows
  8. # and columns 1 and 2; b is the following array of shape (2, 2):
  9. # [[2 3]
  10. # [6 7]]
  11. b = a[:2, 1:3]
  12. # A slice of an array is a view into the same data, so modifying it
  13. # will modify the original array.
  14. print(a[0, 1]) # Prints "2"
  15. b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
  16. print(a[0, 1]) # Prints "77"

与matlab不同的是,切片时使用单个数字索引和使用冒号的索引的结果维度是不同的,例如

  1. import numpy as np
  2. # Create the following rank 2 array with shape (3, 4)
  3. # [[ 1 2 3 4]
  4. # [ 5 6 7 8]
  5. # [ 9 10 11 12]]
  6. a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
  7. # Two ways of accessing the data in the middle row of the array.
  8. # Mixing integer indexing with slices yields an array of lower rank,
  9. # while using only slices yields an array of the same rank as the
  10. # original array:
  11. row_r1 = a[1, :] # Rank 1 view of the second row of a
  12. row_r2 = a[1:2, :] # Rank 2 view of the second row of a
  13. print(row_r1, row_r1.shape) # Prints "[5 6 7 8] (4,)"
  14. print(row_r2, row_r2.shape) # Prints "[[5 6 7 8]] (1, 4)"
  15. # We can make the same distinction when accessing columns of an array:
  16. col_r1 = a[:, 1]
  17. col_r2 = a[:, 1:2]
  18. print(col_r1, col_r1.shape) # Prints "[ 2 6 10] (3,)"
  19. print(col_r2, col_r2.shape) # Prints "[[ 2]
  20. # [ 6]
  21. # [10]] (3, 1)"

这里有一个较为奇怪的整数索引的方式,但这种表达方便创建数组。

  1. import numpy as np
  2. a = np.array([[1,2], [3, 4], [5, 6]])
  3. # An example of integer array indexing.
  4. # The returned array will have shape (3,) and
  5. print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
  6. # The above example of integer array indexing is equivalent to this:
  7. print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
  8. # When using integer array indexing, you can reuse the same
  9. # element from the source array:
  10. print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
  11. # Equivalent to the previous integer array indexing example
  12. print(np.array([a[0, 1], a[0, 1]])) # Prints "[2 2]"
  1. # Create a new array from which we will select elements
  2. a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
  3. print(a) # prints "array([[ 1, 2, 3],
  4. # [ 4, 5, 6],
  5. # [ 7, 8, 9],
  6. # [10, 11, 12]])"
  7. # Create an array of indices
  8. b = np.array([0, 2, 0, 1])
  9. # Select one element from each row of a using the indices in b
  10. print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]"
  11. # Mutate one element from each row of a using the indices in b
  12. a[np.arange(4), b] += 10
  13. print(a) # prints "array([[11, 2, 3],
  14. # [ 4, 5, 16],
  15. # [17, 8, 9],
  16. # [10, 21, 12]])

利用布尔表达式进行索引

  1. import numpy as np
  2. a = np.array([[1,2], [3, 4], [5, 6]])
  3. bool_idx = (a > 2) # Find the elements of a that are bigger than 2;
  4. # this returns a numpy array of Booleans of the same
  5. # shape as a, where each slot of bool_idx tells
  6. # whether that element of a is > 2.
  7. print(bool_idx) # Prints "[[False False]
  8. # [ True True]
  9. # [ True True]]"
  10. # We use boolean array indexing to construct a rank 1 array
  11. # consisting of the elements of a corresponding to the True values
  12. # of bool_idx
  13. print(a[bool_idx]) # Prints "[3 4 5 6]"
  14. # We can do all of the above in a single concise statement:
  15. print(a[a > 2]) # Prints "[3 4 5 6]"

关于数组的索引就只介绍一小部分,当有需要时请查看官方文档深入学习。https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

数组的元素类型可以根据需求进行定义

  1. import numpy as np
  2. x = np.array([1, 2]) # Let numpy choose the datatype
  3. print(x.dtype) # Prints "int64"
  4. x = np.array([1.0, 2.0]) # Let numpy choose the datatype
  5. print(x.dtype) # Prints "float64"
  6. x = np.array([1, 2], dtype=np.int64) # Force a particular datatype
  7. print(x.dtype) # Prints "int64"

array的数学运算,(注意与matlab不同,乘除法是每一个位置的元素乘除法,不是矩阵运算)

  1. import numpy as np
  2. x = np.array([[1,2],[3,4]], dtype=np.float64)
  3. y = np.array([[5,6],[7,8]], dtype=np.float64)
  4. # Elementwise sum; both produce the array
  5. # [[ 6.0 8.0]
  6. # [10.0 12.0]]
  7. print(x + y)
  8. print(np.add(x, y))
  9. # Elementwise difference; both produce the array
  10. # [[-4.0 -4.0]
  11. # [-4.0 -4.0]]
  12. print(x - y)
  13. print(np.subtract(x, y))
  14. # Elementwise product; both produce the array
  15. # [[ 5.0 12.0]
  16. # [21.0 32.0]]
  17. print(x * y)
  18. print(np.multiply(x, y))
  19. # Elementwise division; both produce the array
  20. # [[ 0.2 0.33333333]
  21. # [ 0.42857143 0.5 ]]
  22. print(x / y)
  23. print(np.divide(x, y))
  24. # Elementwise square root; produces the array
  25. # [[ 1. 1.41421356]
  26. # [ 1.73205081 2. ]]
  27. print(np.sqrt(x))

矩阵乘法采用dot

  1. import numpy as np
  2. x = np.array([[1,2],[3,4]])
  3. y = np.array([[5,6],[7,8]])
  4. v = np.array([9,10])
  5. w = np.array([11, 12])
  6. # Inner product of vectors; both produce 219
  7. print(v.dot(w))
  8. print(np.dot(v, w))
  9. # Matrix / vector product; both produce the rank 1 array [29 67]
  10. print(x.dot(v))
  11. print(np.dot(x, v))
  12. # Matrix / matrix product; both produce the rank 2 array
  13. # [[19 22]
  14. # [43 50]]
  15. print(x.dot(y))
  16. print(np.dot(x, y))

一些有用的矩阵运算方法,例如sum

  1. import numpy as np
  2. x = np.array([[1,2],[3,4]])
  3. print(np.sum(x)) # Compute sum of all elements; prints "10"
  4. print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]"
  5. print(np.sum(x, axis=1)) # Compute sum of each row; prints "[3 7]"

当需要使用某些函数时,进行搜索https://docs.scipy.org/doc/numpy/reference/routines.math.html

矩阵转置

  1. import numpy as np
  2. x = np.array([[1,2], [3,4]])
  3. print(x) # Prints "[[1 2]
  4. # [3 4]]"
  5. print(x.T) # Prints "[[1 3]
  6. # [2 4]]"
  7. # Note that taking the transpose of a rank 1 array does nothing:
  8. v = np.array([1,2,3])
  9. print(v) # Prints "[1 2 3]"
  10. print(v.T) # Prints "[1 2 3]"

广播机制:numpy中一个重要而有用的机制,可以将小的矩阵进行扩展后与大矩阵进行运算,省for循环,提高运算速度。

  1. import numpy as np
  2. # We will add the vector v to each row of the matrix x,
  3. # storing the result in the matrix y
  4. x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
  5. v = np.array([1, 0, 1])
  6. y = np.empty_like(x) # Create an empty matrix with the same shape as x
  7. # Add the vector v to each row of the matrix x with an explicit loop
  8. for i in range(4):
  9. y[i, :] = x[i, :] + v
  10. # Now y is the following
  11. # [[ 2 2 4]
  12. # [ 5 5 7]
  13. # [ 8 8 10]
  14. # [11 11 13]]
  15. print(y)
  1. import numpy as np
  2. # We will add the vector v to each row of the matrix x,
  3. # storing the result in the matrix y
  4. x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
  5. v = np.array([1, 0, 1])
  6. vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other
  7. print(vv) # Prints "[[1 0 1]
  8. # [1 0 1]
  9. # [1 0 1]
  10. # [1 0 1]]"
  11. y = x + vv # Add x and vv elementwise
  12. print(y) # Prints "[[ 2 2 4
  13. # [ 5 5 7]
  14. # [ 8 8 10]
  15. # [11 11 13]]"

还能更加简洁

  1. import numpy as np
  2. # We will add the vector v to each row of the matrix x,
  3. # storing the result in the matrix y
  4. x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
  5. v = np.array([1, 0, 1])
  6. y = x + v # Add v to each row of x using broadcasting
  7. print(y) # Prints "[[ 2 2 4]
  8. # [ 5 5 7]
  9. # [ 8 8 10]
  10. # [11 11 13]]"

我们整理一些广播broadcasting的规则:

1、两个数组的维数不相同,低维度的扩展维度

2、两个数组在某个维度上size相同或小的size是1

3、广播相当于沿着size为1的地方进行复制

下面用例子来展示一下广播

  1. import numpy as np
  2. # Compute outer product of vectors
  3. v = np.array([1,2,3]) # v has shape (3,)
  4. w = np.array([4,5]) # w has shape (2,)
  5. # To compute an outer product, we first reshape v to be a column
  6. # vector of shape (3, 1); we can then broadcast it against w to yield
  7. # an output of shape (3, 2), which is the outer product of v and w:
  8. # [[ 4 5]
  9. # [ 8 10]
  10. # [12 15]]
  11. print(np.reshape(v, (3, 1)) * w)
  12. # Add a vector to each row of a matrix
  13. x = np.array([[1,2,3], [4,5,6]])
  14. # x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
  15. # giving the following matrix:
  16. # [[2 4 6]
  17. # [5 7 9]]
  18. print(x + v)
  19. # Add a vector to each column of a matrix
  20. # x has shape (2, 3) and w has shape (2,).
  21. # If we transpose x then it has shape (3, 2) and can be broadcast
  22. # against w to yield a result of shape (3, 2); transposing this result
  23. # yields the final result of shape (2, 3) which is the matrix x with
  24. # the vector w added to each column. Gives the following matrix:
  25. # [[ 5 6 7]
  26. # [ 9 10 11]]
  27. print((x.T + w).T)
  28. # Another solution is to reshape w to be a column vector of shape (2, 1);
  29. # we can then broadcast it directly against x to produce the same
  30. # output.
  31. print(x + np.reshape(w, (2, 1)))
  32. # Multiply a matrix by a constant:
  33. # x has shape (2, 3). Numpy treats scalars as arrays of shape ();
  34. # these can be broadcast together to shape (2, 3), producing the
  35. # following array:
  36. # [[ 2 4 6]
  37. # [ 8 10 12]]
  38. print(x * 2)

更多关于Numpy的内容,请看官方文件http://docs.scipy.org/doc/numpy/reference/

SciPy

SciPy库基于Numpy库,提供了许多操作数组array的函数,官方文件http://docs.scipy.org/doc/scipy/reference/index.html

图片操作

  1. from scipy.misc import imread, imsave, imresize
  2. # Read an JPEG image into a numpy array
  3. img = imread('assets/cat.jpg')
  4. print(img.dtype, img.shape) # Prints "uint8 (400, 248, 3)"
  5. # We can tint the image by scaling each of the color channels
  6. # by a different scalar constant. The image has shape (400, 248, 3);
  7. # we multiply it by the array [1, 0.95, 0.9] of shape (3,);
  8. # numpy broadcasting means that this leaves the red channel unchanged,
  9. # and multiplies the green and blue channels by 0.95 and 0.9
  10. # respectively.
  11. img_tinted = img * [1, 0.95, 0.9]
  12. # Resize the tinted image to be 300 by 300 pixels.
  13. img_tinted = imresize(img_tinted, (300, 300))
  14. # Write the tinted image back to disk
  15. imsave('assets/cat_tinted.jpg', img_tinted)

读写matlab文件

scipy.io.loadmat 与scipy.io.savemat,用到请看http://docs.scipy.org/doc/scipy/reference/io.html

’计算点间距离

  1. import numpy as np
  2. from scipy.spatial.distance import pdist, squareform
  3. # Create the following array where each row is a point in 2D space:
  4. # [[0 1]
  5. # [1 0]
  6. # [2 0]]
  7. x = np.array([[0, 1], [1, 0], [2, 0]])
  8. print(x)
  9. # Compute the Euclidean distance between all rows of x.
  10. # d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
  11. # and d is the following array:
  12. # [[ 0. 1.41421356 2.23606798]
  13. # [ 1.41421356 0. 1. ]
  14. # [ 2.23606798 1. 0. ]]
  15. d = squareform(pdist(x, 'euclidean'))
  16. print(d)

Matplotlib

matplotlib.pyplot的作图模块,与matlab中的使用类似

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on a sine curve
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y = np.sin(x)
  6. # Plot the points using matplotlib
  7. plt.plot(x, y)
  8. plt.show() # You must call plt.show() to make graphics appear.

多条曲线、图标题、图例、坐标等

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on sine and cosine curves
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y_sin = np.sin(x)
  6. y_cos = np.cos(x)
  7. # Plot the points using matplotlib
  8. plt.plot(x, y_sin)
  9. plt.plot(x, y_cos)
  10. plt.xlabel('x axis label')
  11. plt.ylabel('y axis label')
  12. plt.title('Sine and Cosine')
  13. plt.legend(['Sine', 'Cosine'])
  14. plt.show()

与matlab相同,利用subplot分区域作图

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on sine and cosine curves
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y_sin = np.sin(x)
  6. y_cos = np.cos(x)
  7. # Set up a subplot grid that has height 2 and width 1,
  8. # and set the first such subplot as active.
  9. plt.subplot(2, 1, 1)
  10. # Make the first plot
  11. plt.plot(x, y_sin)
  12. plt.title('Sine')
  13. # Set the second subplot as active, and make the second plot.
  14. plt.subplot(2, 1, 2)
  15. plt.plot(x, y_cos)
  16. plt.title('Cosine')
  17. # Show the figure.
  18. plt.show()

显示图像

  1. import numpy as np
  2. from scipy.misc import imread, imresize
  3. import matplotlib.pyplot as plt
  4. img = imread('assets/cat.jpg')
  5. img_tinted = img * [1, 0.95, 0.9]
  6. # Show the original image
  7. plt.subplot(1, 2, 1)
  8. plt.imshow(img)
  9. # Show the tinted image
  10. plt.subplot(1, 2, 2)
  11. # A slight gotcha with imshow is that it might give strange results
  12. # if presented with data that is not uint8. To work around this, we
  13. # explicitly cast the image to uint8 before displaying it.
  14. plt.imshow(np.uint8(img_tinted))
  15. plt.show()

 

(0)

相关推荐