为什么用python画图
- GUI太复杂
- Excel太头疼
- python简单免费
什么是matplotlib
一个Python包用于2D绘图
还有很多扩展如:seaborn
# hello world in matplotlib
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
#魔法函数..
x = np.linspace(0,2 * np.pi ,100)
y = np.sin(x)
plt.plot(x,y)
matplotlib架构
- Backend:主要处理吧图显示到哪里和画到哪里?
- Artist:图像显示成什么样
- 最上层,Scripting:pyplot,python语法和API
推荐网站 matplotlib.org 官方网站
一个简单的例子
a = [1,2,3]
b = [4,5,6]
plt.plot(a)#可以生成可视化的图
plt.plot(a,b)
看看坐标轴变化
改变线的形式
plt.plot(a,b,'*')#线的形式
plt.plot(a,b,'--')#线的形式
plt.plot(a,b,'r--')#线的形式
可以同时在一幅图作图
c = [10,8,6]
d = [1,8,3]
plt.plot(a,b,'r--',c,d,'b*')
画曲线图
t = np.arange(0,2,0.1)
print(t.size)
print(t)
s = np.sin(t*np.pi)
print(s)
有关设置
plt.plot(t,s,'r--',label = 'aaaa')
#设置x y label
plt.xlabel('this is x')
plt.ylabel('this is y')
plt.title(' this is a demo')
plt.legend()#样例
plt.plot(t,s,'r--',label = 'aaaa')
plt.plot(t*2,s,'b*',label = 'bbbb')
#设置x y label
plt.xlabel('this is x')
plt.ylabel('this is y')
plt.title(' this is a demo')
plt.legend()#样例
subplot画子图
x = np.linspace(0,5)
y1 = np.sin(np.pi * x)
y2 = np.cos(np.pi * x * 2)
#subplot画子图
plt.subplot(2,1,1)#最后一个1代表2*1第一个子图
plt.plot(x,y1,'b--',label = 'sin(pi * x)')
plt.plot(x,y2,'r--',label = 'cos(pi * pi * 2 ')
plt.xlabel('x value')
plt.ylabel('y value')
plt.legend()
plt.title('this is x y value')
继续使用subplot
plt.subplot(2,2,1)
plt.plot(x,y1,'b--')
plt.ylabel('y1')
plt.xlabel('x')
plt.subplot(2,2,2)
plt.plot(x,y2,'r--')
plt.ylabel('y2')
plt.xlabel('x')
plt.subplot(2,2,3)
plt.subplot(2,2,4)
还可以这样使用
figure,ax = plt.subplots(2,2)
ax[0][0].plot(x,y1)
ax[0][1].plot(x,y2)