您的位置:首页 > 编程语言 > Python开发

CS231n课程Python Numpy教程四:Matplotlib

2017-10-14 17:27 585 查看

1、Matplotlib介绍

matplotlib是一个做图的库,这里简要介绍matplotlib.pyplot模块,功能和MATLAB的做图功能类似。

2、绘图

matplotlib中最终的函数是plot,该函数可以支持你做出2D的图形。如下:

import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
plt.plot(x, y)
plt.show()  # You must call plt.show() to make graphics appear.


这就是一个y=sin(x) {x = 0,0.1,0.2…3*pi}的函数,最后一个参数0.1,取不同大小的值拟合出的曲线的平滑度不同。



只需要少量工作,就可以一次画不同的线,加上标签,坐标轴标志等:

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)

# Plot the points using matplotlib
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()




更多关于plot的信息,参考文档:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot

3、绘制多个图像

可以使用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)

# 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)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()




更多关于subplot的信息,参考文档:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot

4、图像

你可以使用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()


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: