python学习(17)--Matplotlib

来源:互联网 发布:金融行业数据服务企业 编辑:程序博客网 时间:2024/06/12 01:34

Matplotlib是一个画图库,这一节我们提供了简明的教程,使用类似于MATLAB.

画图

matplotlib最重要的函数就是plot,可以让你画出2D的图。例如:

import numpy as npimport matplotlib.pyplot as plt# Compute the x and y coordinates for points on a sine curvex = np.arange(0, 3 * np.pi, 0.1)y = np.sin(x)# Plot the points using matplotlibplt.plot(x, y)plt.show()  # You must call plt.show() to make graphics appear.

运行后得到如下图:
这里写图片描述
我们还可以添加标题,轴坐标等:

import numpy as npimport matplotlib.pyplot as plt# Compute the x and y coordinates for points on sine and cosine curvesx = np.arange(0, 3 * np.pi, 0.1)y_sin = np.sin(x)y_cos = np.cos(x)# Plot the points using matplotlibplt.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()

得到如下图:
这里写图片描述
更多信息可以查看此文档

子图

你也可以画不同类型的子图,例如:

import numpy as npimport matplotlib.pyplot as plt# Compute the x and y coordinates for points on sine and cosine curvesx = 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 plotplt.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()

得到如下图:
这里写图片描述
更多信息请查看此文档

图片

可以使用imshow函数来展示图片。例如:

import numpy as npfrom scipy.misc import imread, imresizeimport matplotlib.pyplot as pltimg = imread('assets/cat.jpg')img_tinted = img * [1, 0.95, 0.9]# Show the original imageplt.subplot(1, 2, 1)plt.imshow(img)# Show the tinted imageplt.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()

结果如图:
这里写图片描述

原创粉丝点击