机器学习绘图库Python Matplotlib.pyplot全网最全面新手教程

本文是Matplotlib.pyplot的全网新手教程,涵盖了绘图、子图和图像绘制。教程源自英文资源,易于理解,旨在帮助初学者掌握Python中的数据可视化。内容包括使用plot函数绘制二维图像,创建带有多条曲线和标签的图表,使用subplot函数布局多子图,以及运用imshow展示图像。
摘要由CSDN通过智能技术生成

最近看到一个讲Matplotlib的英文教程写的很高明,兼收并蓄,简单易懂,特意翻译过来,与君共享。原网址在:http://cs231n.github.io/python-numpy-tutorial/#matplotlib 。


Matplotlib(https://matplotlib.org/)是一个用来绘图的python库,它的matplotlib.pyplot模块提供了一个与MATLAB非常类似的绘图系统。

绘图(Plotting)

matplotlib中最重要的函数就是plot,它可以绘制二维图像,例子如下:

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(),不然图像不会显示出来
plt.show()  

运行上述代码的结果如下:
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()

2
有关plot函数更详细更全面的讲解尽在官方文档:https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot 。

子图(Subplots)

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

# 我要绘制2行1列的子图,现在声明,我要绘制第1个子图啦~
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# 现在声明我要绘制第2个子图啦~
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()

3
关于subplot函数更详细的介绍尽在官方文档:https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot 。

图像(Images)

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

4

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值