绘图相关

SciPy定义了一些用于计算点集之间距离的有用函数。

函数scipy.spatial.distance.pdist计算给定集合中所有点对之间的距离:

import numpy as np

from scipy.spatial.distance import pdist, squareform

# Create the following array where each row is a point in 2D space:

# [[0 1]

#  [1 0]

#  [2 0]]

x = np.array([[0, 1], [1, 0], [2, 0]])

print(x)

# Compute the Euclidean distance between all rows of x.

# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],

# and d is the following array:

# [[ 0.          1.41421356  2.23606798]

#  [ 1.41421356  0.          1.        ]

#  [ 2.23606798  1.          0.        ]]

d = squareform(pdist(x, 'euclidean'))

print(d)

Matplotlib

Matplotlib是一个绘图库。本节简要介绍 matplotlib.pyplot 模块,该模块提供了类似于MATLAB的绘图系统。

绘制

matplotlib中最重要的功能是plot,它允许你绘制2D数据的图像。这是一个简单的例子:

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 3 * np.pi, 0.1)

y_sin = np.sin(x)

y_cos = np.cos(x)

plt.plot(x,y_sin)

plt.plot(x,y_cos)

plt.xlabel('x axis label')-横坐标

plt.ylabel('y axis label')-纵坐标

plt.title('Sine and Cosine')-标题

plt.legend(['Sine','Cosine'])-标识

plt.show()

子图

https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot

你可以使用subplot函数在同一个图中绘制不同的东西。 这是一个例子:

import numpy as np

import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on sine and cosine curves

x = np.arange(0, 3 * np.pi, 0.1)

y_sin = np.sin(x)

y_cos = np.cos(x)

# Set up a subplot grid that has height 2 and width 1,

# and set the first such subplot as active.

plt.subplot(2, 1, 1)-(2,1,2)一起在下方图中

# Make the first plot

plt.plot(x, y_sin)

plt.title('Sine')

# Set the second subplot as active, and make the second plot.

plt.subplot(2, 1, 2)  -(2,1,1)一起在上方图中

plt.plot(x, y_cos)

plt.title('Cosine')

# Show the figure.

plt.show()

图片

你可以使用 imshow 函数来显示一张图片。 这是一个例子:

import numpy as np

from scipy.misc import imread, imresize

import matplotlib.pyplot as plt

img = imread('assets/cat.jpg')

img_tinted = img * [1, 0.95, 0.9]

# Show the original image

plt.subplot(1, 2, 1)

plt.imshow(img)

# Show the tinted image

plt.subplot(1, 2, 2)

# A slight gotcha with imshow is that it might give strange results

# if presented with data that is not uint8. To work around this, we

# explicitly cast the image to uint8 before displaying it.

plt.imshow(np.uint8(img_tinted))

plt.show()

你可能感兴趣的:(绘图相关)