2021-01-30

Matplotib的画图

import matplotlib.pyplot as plt
import numpy as np
1.figure图像

x=np.linspace(-3,3,50)
y1=0.1*x
y2=x**2
plt.figure()
plt.plot(x,y1) #显示图像
plt.figure(num=3,figsize=(8,5),) #图像的序号,figsize图像的长与宽
plt.plot(x,y2)
plt.plot(x,y1,color=‘red’,linewidth=1.0,linstyle=’–’) #线的宽度,线的形式为虚线
plt.show()

2.坐标轴设置1
plt.xlim((-1,2)) #x轴的取值范围
plt.ylim((-2,3)) #y轴的取值范围
plt.xlabel(‘l am x’) #描述x 轴
plt.ylabel(‘l am y’) #描述y轴
new_ticks=np.linspace(-1,2,5)#单位的脚标
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],
[r’ r e a l l y   b a d   α really\ bad\ \alpha really bad α’,r’ b a d bad bad’,r’ n o r m a l normal normal’,r’ g o o d good good’,r’ r e a l l y   g o o d really\ good really good’])
#前面加r:正值表达式,改变字体:前后两边加KaTeX parse error: Undefined control sequence: \ at position 5: ,中间加\̲ ̲ #r'bad\ \alpha$’ 转化为a

3.坐标轴设置2
ax=plt.gca() #gca='get current axis’现在的轴
ax.spines[‘right’].set_color(‘none’) #spines脊梁,框架:右边的轴没有
ax.spines[‘top’].set_color(‘none’) #上边的轴没有
ax.xaxis.set_ticks_position(‘bottom’) #定义下面的轴为x轴,左边的轴为y轴
ax.yaxis.set_ticks_position(‘left’)
ax.spines[‘bottom’].set_position((‘data’,0)) #起始坐标为(0,0)
ax.spines[‘left’].set_position((‘data’,0))

4.legend图例
l1=plt.plot(x,y2,label=‘up’) #给每条线命名up
l2=plt.plot(x,y1,color=‘red’,linewidth=1.0,linestyle=’–’,label=‘down’)
plt.legend(handles=[l1,l2],labels=[‘aaa’,‘bbb’],loc=‘best’)

5.annotation注解
x0=1
y0=2*x0+1
plt.scatter(x0,y0,s=50,color=‘b’) #大小为50,蓝色
plt.plot([x0,x0],[y0,0],‘k–’,lw=2.5) #横坐标都为x0,纵坐标为y0,0,黑色的虚线,宽度为2.5
#方法一
plt.annotate(r’ 2 x + 1 = 2x+1=%s 2x+1=’ % y0,xy=(x0,y0),xycoords=‘data’,xytext=(+30,-30),
textcoords=‘offset points’,fontsize=16,arrowprops=dict(arrowstyle=’->’,connectionstyle=‘arc3,rad=.2’))
xy=(x0,y0),xycoords='data’这部分为啥是xy
#方法二
plt.text(-3.7,3,r’ T h i s   i s   t h e   s o m e   t e x t .   μ   σ i   α t This\ is\ the\ some\ text.\ \mu\ \sigma_i\ \alpha_t This is the some text. μ σi αt’,fontdict={‘size’:16,‘color’:‘red’})

6.坐标轴刻度
for label in ax.get_xticklabels()+ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor=‘white’,edgecolor=‘None’,alpha=0.7))
set_bbox?
7.散点图
n=1024
X=np.random.normal(0,1,n)
Y=np.random.normal(0,1,n)
T=np.arctan2(Y,X) #for color value
plt.scatter(X,Y,s=75,c=T,alpha=0.5) #透明度为0.5
plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))
plt.xticks(())
plt.yticks(())
plt.show()

#import numpy as np
import matplotlib.pyplot as plt
import numpy as np

8.柱状图

n=12
X=np.arange(n)
Y1=(1-X/float((n)))*np.random.uniform(0.5,1.0,n)
Y2=(1-X/float((n)))*np.random.uniform(0.5,1.0,n)
plt.bar(X,+Y1,facecolor=’#9999ff’,edgecolor=‘white’)
plt.bar(X,-Y2,facecolor=’#ff9999’,edgecolor=‘white’)

for x,y in zip(X,Y1): #把X,Y分别传入x.y中
plt.text(x+0.3,y+0.05,’%.2f’%y,ha=‘center’,va=‘bottom’)
for x,y in zip(X,Y2):
plt.text(x+0.3,-y-0.05,’%.2f’%y,ha=‘center’,va=‘bottom’)
plt.xlim((-5,n))
plt.xticks(())
plt.ylim((-1.25,1.25))
plt.yticks(())

9.等高线图
def f(x,y):
return (1-x/2+x5+y3)*np.exp(-x2-y2)
n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
X,Y=np.meshgrid(x,y) #网格的输入化
plt.contourf(x,y,f(X,Y),8,alpha=0.75,cmap= plt.cm.hot)#8:分为10部分,cmap:状态为炎热
C=plt.contour(x,y,f(X,Y),8,color=‘black’,linewidth=5)#等高线
f(X,Y)这个地方不太懂
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())

10.Image图片
a=np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134,0.525083754405,0.651536351379]).reshape(3,3)
#像素
plt.imshow(a,interpolation=‘nearest’,cmap=‘bone’,origin=‘lower’)#图像灰度插值
plt.colorbar(shrink=0.9)#颜色变化图例,压缩90%
plt.xticks(())
plt.yticks(())
plt.show()

11.3D数据
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)
R=np.sqrt(X2+Y2)
#高度的值
Z=np.sin®
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap(‘rainbow’))
#rstride行跨 cstride列跨,越小越密集
ax.coutourf(X,Y,Z,zdir=‘z’,offset=-4,cmap=‘rainbow’)
ax.set_zlim(-1,2)

12.subplot多个显示
plt.figure()
plt.subplot(2,1,1) #创建小图
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])
plt.subplot(2,3,5)
plt.plot([0,1],[0,3])
plt.subplot(2,3,6)
plt.plot([0,1],[0,4])

13.subplot分格显示
#method 1:subplot2grid
plt.figure()
ax1=plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)#占3列,1行
ax1.plot([1,2],[1,2])
ax1.set_title(‘ax1_title’)
ax2=plt.subplot2grid((3,3),(1,0),colspan=2)
ax3=plt.subplot2grid((3,3),(1,2),rowspan=2)
ax4=plt.subplot2grid((3,3),(2,0))
ax5=plt.subplot2grid((3,3),(2,1))

#method 2:gridspec
import matplotlib.gridspec as gridspec
plt.figure()
gs=gridspec.GridSpec(3,3)
ax1=plt.subplot(gs[0,:])
ax2=plt.subplot(gs[1,:2])
ax3=plt.subplot(gs[1:,2])
ax4=plt.subplot(gs[-1,0]) #为啥是-1,-2啊
ax5=plt.subplot(gs[-1,-2])
#method 3:easy to define structure
f,((ax11,ax12),(ax21,ax22))=plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2],[1,2])
plt.tight_layout()

14.图中图
fig=plt.figure()
x=[1,2,3,4,5,6,7]
y=[1,3,4,2,5,8,6]
left,bottom,width,height=0.1,0.1,0.8,0.8
ax1=fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,‘r’)
ax1.set_xlabel(‘x’)
ax1.set_ylabel(‘y’)
ax1.set_title(‘title’)

left,bottom,width,height=0.2,0.6,0.25,0.25
ax1=fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,‘b’)
ax1.set_xlabel(‘x’)
ax1.set_ylabel(‘y’)
ax1.set_title(‘title_inside1’)

left,bottom,width,height=0.6,0.2,0.25,0.25
ax1=fig.add_axes([left,bottom,width,height])
ax1.plot(y[::-1],x,‘c’)
ax1.set_xlabel(‘x’)
ax1.set_ylabel(‘y’)
ax1.set_title(‘title_inside2’)
15.次坐标轴
x=np.arange(0,10,0.1)
y1=0.05x**2
y2=-1
y1
fig,ax1=plt.subplots()
ax2=ax1.twinx()
ax1.plot(x,y1,‘g-’)
ax2.plot(x,y2,‘b–’)
ax1.set_xlabel(‘X data’)
ax1.set_ylabel(‘Y1’,color=‘g’)
ax1.set_ylabel(‘Y2’,color=‘b’ )

16.Animation动画
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=animation,frames=100,init_func=init,interval=20,blit=False)#频率为20,blit是否更新
plt.show()

总结:Matplotib的画图基础的知识看完视频,基本都理解了,但可能记不住一些方法和单词,还有些地方不太懂的已着重标记,学完Matplotib画图之后,感觉能跟着敲出来,但有时做出的图和视频里展示的不一样,比如Animation动画,我的都是静态的,还有3D数据可以多角度展示,我的不能动,学完之后收获挺大的

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值