画出第一个基本图像
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = x*2+1
plt.plot(x, y)
plt.show()
用两个窗口画出两个图像
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y1 = x*2+1
y2 = x**2
plt.figure()
line1 = plt.plot(x, y1, color='red', linestyle='--')[0]
# 在窗口加其他plot就会画别的线,可以改改颜色
# figure能配置某些参数,看看帮助
plt.figure()
line2 = plt.plot(x, y2)[0]
# 设置x轴的长度,同理有ylim
plt.xlim((0, 100))
# x轴标签为num,同理ylabel
plt.xlabel('num')
# 换掉刻度值
plt.xticks(要被更换的,想更换的)
# 添加图例
plt.legend(handles=[line1, line2],labels=['aa','bb'],loc='best')
# 在曲线上加一个点
x0 = 0.5
y0 = x0**2
plt.scatter(x0, y0)
# 将这个点做出现交于轴
plt.plot([x0, x0], [y0, 0], 'k')
# 将这个点写个注释
plt.annotate('a point', (x0, y0))
plt.show()
画散点图:
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y, X)
# XY没啥说的,s:表示的是大小,c:表示的是色彩或颜色序列,alpha:标量,0-1之间
plt.scatter(X, Y, s=75, c=T, alpha=0.5)
plt.ylim((-1.5, 1.5))
plt.xlim((-1.5, 1.5))
plt.show()
画柱状图
X = np.arange(0, 10, 1)
Y = np.arange(0, 10, 1)
plt.bar(x=X, height=Y)
# 将柱状图标注Y值
for x,y in zip(X,Y):
plt.text(x+0.4,y+0.05,'%f'%y)
plt.show()
画3D图像
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 创建窗口
fig = plt.figure()
# 向窗口添加三维坐标
ax = Axes3D(fig)
# 创建X,Y
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
# 计算Z的值
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, cmap=plt.get_cmap('rainbow'))
plt.show()
一个图框有多个图像
plt.figure()
# 两行两列,第一个图像
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
# 两行两列,第二个图像
plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 2])
# 两行两列,第三个图像
plt.subplot(2, 2, 3)
plt.plot([0, 1], [0, 3])
plt.show()
# 一个图像占两个图像的位置
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
# 两个小的分居第二行
plt.subplot(2, 2, 3)
plt.plot([0, 1], [0, 2])
plt.subplot(2, 2, 4)
plt.plot([0, 1], [0, 3])
一个图框有多个不同大小图像
plt.figure()
# 3*3个框,第一幅图像从起始开始,占3列一行
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([0, 1], [0, 1])
# 3*3个框,第二幅图像从第二行起始开始,占1列两行
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=1, rowspan=2)
ax2.plot([0, 1], [0, 2])
# 3*3个框,第二幅图像从第二行第二列起始开始,占2列两行
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2, rowspan=2)
ax3.plot([0, 1], [0, 4])
plt.show()
次坐标轴,两条线用的Y轴数值和间隔不同
plt.figure()
ax1 = plt.subplot()
ax2 = ax1.twinx()
x = np.linspace(-1, 1, 50)
y1 = x * 2 + 1
y2 = x ** 3
ax1.plot(x, y1, 'g')
ax2.plot(x, y2, 'b')
ax1.set_ylabel('y1', color='g')
ax2.set_ylabel('y2', color='b')
plt.show()