matplotlib 画图
程序员文章站
2022-02-05 19:28:11
...
- 散点图
x1 = np.random.normal(0,1,500)
y1 = np.random.normal(0,1,500)
x2 = np.random.normal(0,1,100)
y2 = np.random.normal(0,1,100)
plt.scatter(x1,y1,c='r',s=40,alpha=0.5)
plt.scatter(x2,y2,c='b',s=40,alpha=0.4)
plt.show()
- 直方图
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = x*3+10
# CTRL+B 看源码
# plt.bar(x,-y,color='r',width=0.5,facecolor='#9999ff')
# plt.show()
x = np.arange(10)
y = 2**x + 10
plt.bar(x,y,facecolor='#9999ff',edgecolor='white')
for x,y in zip(x,y):
plt.text(x+0.4,y,'%.2f' % y,ha='center',va='bottom')
plt.show()
- 等高线图
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
x = np.linspace(-3,3,100)
y = np.linspace(-3,3,100)
X,Y = np.meshgrid(x,y)
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
C = plt.contour(X,Y,f(X,Y),8,colors='black',linewidth=.5)
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
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 = np.arange(-4,4,0.25)
y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(x,y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
# ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
# ax.set_zlim(-2,2)
plt.show()
- 多图
plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,1])
plt.subplot(235)
plt.plot([0,1],[0,1])
plt.subplot(236)
plt.plot([0,1],[0,1])
plt.show()
- 动态图
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
fig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
line, = ax.plot(x,np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig=fig,func=animate,init_func=init,interval=20)
plt.show()