简单的线条
matplotlib
的 figure
就是一个 单独的 figure
小窗口, 小窗口里面还可以有更多的小图片.
使用import
导入模块matplotlib.pyplot
,并简写成plt
使用import
导入模块numpy
,并简写成np
import matplotlib.pyplot as plt
import numpy as np
使用np.linspace
定义x
:范围是(-3,3);个数是50. 仿真一维数据组(x ,y1)表示曲线1. 仿真一维数据组(x ,y2)表示曲线2.
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
使用plt.figure
定义一个图像窗口. 使用plt.plot
画(x ,y1)曲线.
plt.figure()
plt.plot(x, y1)
plt.show()
使用plt.figure
定义一个图像窗口:编号为3;大小为(8, 5). 使用plt.plot
画(x ,y2)曲线. 使用plt.plot
画(x ,y1)曲线,曲线的颜色属性(color
)为红色;曲线的宽度(linewidth
)为1.0;曲线的类型(linestyle
)为虚线. 使用plt.show
显示图像.
plt.figure(num=3, figsize=(8, 5),)
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.show()
创建多个子图的几种方式
第一种方式
fig = plt.figure(figsize=(15, 5))
ax1 = fig.add_subplot(1, 3, 1)
ax2 = fig.add_subplot(1, 3, 2)
ax3 = fig.add_subplot(1, 3, 3)
ax1.plot([1, 2, 3])
ax2.plot([3, 2, 1])
ax3.plot([2, 2, 6])
plt.show()
第二种方式
fig2, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].plot([1, 2, 3])
axes[1].plot([3, 2, 1])
axes[2].plot([2, 2, 2])
plt.show()
如果axes是多维对象,则需要传入多个坐标值,如axes[1, 1].
fig3, axes = plt.subplots(2, 3, figsize=(12, 10))
axes[0, 0].plot([1, 2, 3])
axes[0, 1].plot([3, 2, 1])
axes[0, 2].plot([2, 2, 2])
plt.show()
第三种方式(不推荐)
plt.figure(1, figsize=(10, 10)) # the first figure
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4, 5, 6])