Matplotlib再来一次 文章目录 一、基础用法 二、figure图像 三、设置坐标轴 四、legend图例 五、标注 六、散点图 七、直方图
Matplotlib再来一次
文章目录
- 一、基础用法
- 二、figure图像
- 三、设置坐标轴
- 四、legend图例
- 五、标注
- 六、散点图
- 七、直方图
- 八、等高线图
- 九、3D图
- 十、subplot
- 十一、动态图
配合
机器学习食用更佳。
一、基础用法
- 画直线
import numpy as np
%matplotlib inlinex = np.linspace(-1,1,100)#从-1到1生成100个点
y = 2*x + 1
plt.plot(x,y)
plt.show()
二、figure图像
- 不同图像在不同的figure中
- 改变图像大小
- plt.plot(x,y2,color=‘blue’,linewidth=5.0,linestyle=’-’)
y1 = 2*x+1
y2 = x ** 2
plt.figure()
plt.plot(x,y1)
plt.figure(figsize=(8,5)) # 改变图像大小
plt.plot(x,y2)
plt.show()
y1 = 2 *x + 1
y2 = x ** 2
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')[<matplotlib.lines.Line2D at 0x7fc5d44dd6a0>]
三、设置坐标轴
- xlim、ylim限制范围
- xlabel、ylabel描述
- xticks、yticks 修改坐标范围或者类型
- 画坐标图
y1 = 2 *x + 1
y2 = x ** 2
# xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
# xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')[<matplotlib.lines.Line2D at 0x7fc5d4727470>]
print(new_ticks)[-2. -1.6 -1.2 -0.8 -0.4 0. 0.4 0.8 1.2 1.6 2. ]x = np.linspace(-3,3,100)
y1 = 2 *x + 1
y2 = x ** 2
# xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
# xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
plt.xticks(new_ticks)
plt.yticks([-2,-1,0,1,2,3],['level0','level1','level2','level3','level4','level5'])
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')[<matplotlib.lines.Line2D at 0x7fc5d60c52e8>]
y1 = 2*x + 1
y2 = x**2
#xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
#xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')
new_ticks = np.linspace(-2,2,11)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-1,0,1,2,3],
['level1','level2','level3','level4','level5'])
# 得到当前的坐标
ax = plt.gca()
ax.spines['right'].set_color('red') # 把右边颜色变成红色
ax.spines['top'].set_color('none') # 把上边去掉
# 把x轴的刻度设置为‘bottom’
# 把y轴的刻度设置为‘left’
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 设置bottom对应到0点
# 设置left对应到0点
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
plt.show()[-2. -1.6 -1.2 -0.8 -0.4 0. 0.4 0.8 1.2 1.6 2. ]
四、legend图例
legend
l1, = plt.plot(x,y1,color=‘red’,linewidth=1.0,linestyle=’–’)
l2, = plt.plot(x,y2,color=‘blue’,linewidth=5.0,linestyle=’-’)
plt.legend(handles=[l1,l2],labels=[‘test1’,‘test2’],loc=‘best’) # loc是图例位置 loc:best是自动选择最佳位置
x = np.linspace(-3,3,100)y1 = 2*x + 1
y2 = x**2
#xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
#xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
l1, = plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
l2, = plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')
plt.legend(handles=[l1,l2],labels=['test1','test2'],loc='best') # loc是图例位置 loc:best是自动选择最佳位置
new_ticks = np.linspace(-2,2,11)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-1,0,1,2,3],
['level1','level2','level3','level4','level5'])
plt.show()[-2. -1.6 -1.2 -0.8 -0.4 0. 0.4 0.8 1.2 1.6 2. ]
五、标注
x = np.linspace(-1,1,100)y1 = 2*x + 1
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='-')
#gca get current axis
ax = plt.gca()
#把右边和上边的边框去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#把x轴的刻度设置为‘bottom’
#把y轴的刻度设置为‘left’
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#设置bottom对应到0点
#设置left对应到0点
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
x0 = 0.5
y0 = 2*x0 + 1
#画点
plt.scatter(x0,y0,s=50,color='b')
#画虚线
plt.plot([x0,x0],[y0,0],'k--',lw=2)
plt.annotate(r'$2x+1=%s$' % y0,xy=(x0,y0),xytext=(+30,-30),textcoords='offset points',fontsize=16,
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
plt.text(-1,2,r'$this\ is\ the\ text$',fontdict={'size':'16','color':'r'})
plt.show()
六、散点图
plt.scatter(x,y,s=50,c=‘b’,alpha=0.5) # alpha透明度
plt.scatter(np.arange(5),np.arange(5))plt.show()
y = np.random.normal(0,1,500)
plt.scatter(x,y,s=50,c='b',alpha=0.5) # alpha透明度
plt.xlim((-2,2))
plt.ylim((-2,2))
plt.xticks(())
plt.yticks(())
plt.show()
七、直方图
- plt.bar(x,y,facecolor=’#9999ff’,edgecolor=‘white’) # edgecolor 边框颜色
y = 2**x + 10
plt.bar(x,y)
plt.show()
y = 2**x + 10
plt.bar(x,-y)
plt.show()
y = 2**x + 10
plt.bar(x,y,facecolor='#9999ff',edgecolor='white') # edgecolor 边框颜色
plt.show()
y = 2**x + 10
plt.bar(x,y,facecolor='#9999ff',edgecolor='white')
for x,y in zip(x,y):
plt.text(x,y,'%.2f' % y,ha='center',va='bottom')
plt.show()
八、等高线图
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’,linewidths=.5)
plt.clabel(C,inline=True,fontsize=10)
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)
plt.xticks(())
plt.yticks(())
plt.show()
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',linewidths=.5)
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
九、3D图
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)
import numpy as np
from mpl_toolkits.mplot3d import Axes3Dfig = 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'))
plt.show()
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()
十、subplot
plt.figure()plt.subplot(2,2,1)
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)
plt.plot([0,1],[0,1])
plt.subplot(223)
plt.plot([0,1],[0,1])
plt.subplot(224)
plt.plot([0,1],[0,1])
plt.show()
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 pltimport numpy as np
from matplotlib import animationfig,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()