matplotlib可视化分析学习
在B站搜的视频看:https://b23.tv/wT53Kh
一、基本图形画法
1.散点图:plt.sactter(x轴数据,y轴数据,c=颜色,s=点大小,alpha=透明度,marker=点形状)
2.折线图:plt.plot(x轴数据,y轴数据,linestyle=线形,color=颜色,marker=点形状)
3.条形图:纵向图:plt.bar(横坐标,数据,密度)
横向图:plt.barh()
4.直方图:plt.hist(x=数据,bins=条形分组个数,color=颜色,normed=True标准化)
5.饼状图:plt.pie(x=数据,labels=名称,autopct=‘%.0f%'占比例,explod=扇形块到中心的距离,shadow=True边缘阴影)
使饼状图为正圆:plt.axes(aspect=1)
6.箱型图:plt.boxplot(数据,sym=异常点的形状,whis=1.5异常值显示范围,labels=多个数据的名称)
7.极坐标图:
import numpy as np from matplotlib import pyplot as plt r=np.arange(1,6,1) theta=[0,np.pi/2,np.pi,3*np.pi/2,2*np.pi] ax1=plt.subplot(221,projection='polar')#定义为极坐标 ax1.plot(theta,r,color='r',linewidth=3) ax1.grid(True) r=np.empty(5) r.fill(5) theta=[0,np.pi/2,np.pi,3*np.pi/2,2*np.pi] ax2=plt.subplot(222,projection='polar')#定义为极坐标 ax2.plot(theta,r,color='r',linewidth=3) ax2.grid(True) r=np.empty(9) r.fill(5) pi_two=np.pi*2 theta=[0,pi_two/8,pi_two/4,3*pi_two/8,pi_two/2,5*pi_two/8,6*pi_two/8,7*pi_two/8,pi_two] ax3=plt.subplot(223,projection='polar')#定义为极坐标 ax3.plot(theta,r,color='r',linewidth=3) ax3.grid(True) plt.show()
二、颜色和样式
1.颜色
1)八种内建默认颜色缩写:b:blue,g:green,r:red,c:cyan,m:magenta,y:yellow,k:black,w:white
2)灰色阴影:color=‘0.5
3)十六进制:colot='#FF00FF'
4)RGB元组:color=(0.1,0.2,0.3)
2.点、线的样式
1)marker='...' 23种点样式
2)四种线形:-实线
--虚线
-.点划线
:点线
3)样式字符串,将颜色、点型、线型写成一个字符串。eg.cx-
三、面向对象
1.子图subplot
fig=plt.figure() ax=fig.add_subplot(111)#参数分别为,子图总行数,子图总列数,当前子图位置
ax.plot(x,y)
ax.show()
2.多图
fig1=plt.figure()
fig2=plt.figure()
3.网格:plt..grid(True,color=颜色,linewidth=网络线宽,linestyle=网络线型)
4.图例
先定义:plt.plot(数据,labels=标签名)
plt.legend(图例名称,loc图列位置,ncol=图例列的个数)
5.坐标轴范围
plt.axis():输出一个数组(x轴最小坐标,x轴最大坐标,y轴最小坐标,y轴最大坐标),也可填入赋值
plt.xlim():限制x轴的最大最小坐标
6.坐标轴刻度
plt.plot(x,y)
ax=plt.gca()
ax.locator_params('y'加了就是改变y轴,nbins=坐标刻度数)
7.绘制时间为刻度的图
import datetime import numpy as np from matplotlib import pyplot as plt import matplotlib as mpl fig = plt.figure()#面向对象画布 start=datetime.datetime(2021,11,14)#起始时间 stop=datetime.datetime(2022,11,14)#终止时间 delta = datetime.timedelta(days=1)#时间间隔 dates = mpl.dates.drange(start,stop,delta)#建立时间横轴数据 y= np.random.rand(len(dates))#随机数据 ax = plt.gca()#获取当前画布 ax.plot_date(dates,y,linestyle='-',marker='')#画出时间刻度折线图 plt.show()#显示图片
8.添加坐标轴
import numpy as np from matplotlib import pyplot as plt x = np.arange(2,20,1) y1 = x*x y2 = np.log(x) fig = plt.figure() ax1 = fig.add_subplot(111)#建立图表,共一行一列,第一个图表 ax1.plot(x,y1) ax1.set_ylabel('Y1') ax2 = ax1.twinx()#添加另一个x坐标轴 ax2.plot(x,y2,'r') ax2.set_ylabel('Y2') ax1.set_xlabel('Compare Y1 and Y2') plt.show()
也可添加y轴
import numpy as np from matplotlib import pyplot as plt x = np.arange(2,20,1) y1 = x*x y2 = np.log(x) fig = plt.figure() ax1 = fig.add_subplot(111)#建立图表,共一行一列,第一个图表 ax1.plot(y1,x) ax1.set_ylabel('Y1') ax2 = ax1.twiny() ax2.plot(y2,x,'r') ax2.set_ylabel('Y2') ax1.set_xlabel('Compare Y1 and Y2') plt.show()
9.图像注释
import numpy as np from matplotlib import pyplot as plt x = np.arange(-10,11,1) y = x*x plt.plot(x,y) plt.annotate('this is the bottom',xy=(0,1),xytext=(0,20),arrowprops=dict(facecolor='r',headlength=7,headwidth=10,width=5)) ''' 定义注释annotate xy:注释箭头(也有可能是其他形状)的起始点 xytext:注释文字的起始点 arrowprops: facecolor:颜色 headlength:箭头尖部的长度 headwidth:箭头尖部的宽度 width:箭头箭身的宽度 ''' plt.show()
10.文字
import numpy as np from matplotlib import pyplot as plt x = np.arange(-10,11,1) y = x*x plt.plot(x,y) plt.text(0,40,'function:y=x*x',family='serif',size=20,color='r',style='italic',weight=2,bbox=dict(facecolor='r',alpha=0.2)) ''' 中间坐标为起始位置 family:字体格式,自行百度 size:字体大小 color:颜色 style:字体,斜体 weight:粗体 bbox:注释边框 facecolor:颜色 alpha:透明度 ''' plt.text(0,20,'function:y=x*x') plt.show()
11.画数学公式
import numpy as np from matplotlib import pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlim([1,7]) ax.set_ylim([1,5]) ax.text(2,4,r"$ \alpha_i \beta_j \pi \lambda \omega $",size=25) ax.text(4,4,r"$ \sin(0)=\cos(\frac{\pi}{2}) $",size=20) ax.text(2,2,r"$ \lim_{x \rightarrow y}(\frac{1}{x^3}) $",size=25) ax.text(4,2,r"$ \sqrt[4]{x}=\sqrt{y} $",size=25) plt.show()
12.区域填充
import numpy as np from matplotlib import pyplot as plt x=np.linspace(0,5*np.pi,1000) y1 = np.sin(x) y2 = np.sin(2*x) plt.plot(x,y1) plt.plot(x,y2) plt.fill(x,y1,'b',alpha=0.2) plt.fill(x,y2,'r',alpha=0.2) plt.show()
import numpy as np from matplotlib import pyplot as plt x=np.linspace(0,5*np.pi,1000) y1 = np.sin(x) y2 = np.sin(2*x) fig = plt.figure() ax = plt.gca() ax.plot(x,y1,x,y2,color='black') ax.fill_between(x,y1,y2,facecolor='blue') plt.show()
import numpy as np from matplotlib import pyplot as plt x=np.linspace(0,5*np.pi,1000) y1 = np.sin(x) y2 = np.sin(2*x) fig = plt.figure() ax = plt.gca() ax.plot(x,y1,color='r') ax.plot(x,y2,color='b') ax.fill_between(x,y1,y2,where= y1>y2 , facecolor='y') ax.fill_between(x,y1,y2,where= y1<y2 , facecolor='g') plt.show()
13.形状
import numpy as np from matplotlib import pyplot as plt import matplotlib.patches as maptches fig ,ax = plt.subplots() xy1 = np.array([0.2,0.2]) xy2 = np.array([0.2,0.8]) xy3 = np.array([0.8,0.2]) xy4 = np.array([0.8,0.8]) circle = maptches.Circle(xy1,0.1) ax.add_patch(circle) rect=maptches.Rectangle(xy2,0.2,0.1,color='r')#坐标代表左下角点的位置 ax.add_patch(rect) polygom=maptches.RegularPolygon(xy3,5,0.1,color='g')#边数,圆心到点的距离 ax.add_patch(polygom) ellipse = maptches.Ellipse(xy4,0.4,0.2,color='y') ax.add_patch(ellipse) plt.axis('equal') plt.grid() plt.show()
四、美化
1.美化前
import numpy as np from matplotlib import pyplot as plt fig ,ax = plt.subplots(2,2)#四张图 ax1,ax2,ax3,ax4=ax.ravel()#分别叫四个名字 x,y=np.random.normal(size=(2,100))#随机生成正泰分布数组 ax1.plot(x,y,'o')#画出点状 x=np.arange(0,10) y=np.arange(0,10) ncolots=len(plt.rcParams['axes.prop_cycle'])#每根线的颜色循环变更 shift=np.linspace(0,10,ncolots)#产生ncolor个0到10之间的数 for s in shift: ax2.plot(x,y+s,'-')#画出直线图 x=np.arange(5) y1,y2,y3=np.random.randint(1,25,size=(3,5))#随机产生25以内的整数 width=0.25 ax3.bar(x,y1,width) ax3.bar(x+width,y2,width,color=plt.rcParams['axes.prop_cycle'].by_key()['color'][1]) ax3.bar(x+width*2,y3,width,color=plt.rcParams['axes.prop_cycle'].by_key()['color'][2]) for i in range(len(plt.rcParams['axes.prop_cycle'])): xy=np.random.normal(size=2)#随机生成以2为标准差的正泰分布数组 ax4.add_patch(plt.Circle(xy,radius=0.3,color=plt.rcParams['axes.prop_cycle'].by_key()['color'][i])) ax4.axis('equal') plt.show()
美化后:
plt.style.use()函数
import numpy as np from matplotlib import pyplot as plt import matplotlib.patches as maptches plt.style.use('ggplot') fig ,ax = plt.subplots(2,2) ax1,ax2,ax3,ax4=ax.ravel() x,y=np.random.normal(size=(2,100)) ax1.plot(x,y,'o') x=np.arange(0,10) y=np.arange(0,10) ncolots=len(plt.rcParams['axes.prop_cycle'])#每根线的颜色循环变更 shift=np.linspace(0,10,ncolots) for s in shift: ax2.plot(x,y+s,'-') x=np.arange(5) y1,y2,y3=np.random.randint(1,25,size=(3,5)) width=0.25 ax3.bar(x,y1,width) ax3.bar(x+width,y2,width,color=plt.rcParams['axes.prop_cycle'].by_key()['color'][1]) ax3.bar(x+width*2,y3,width,color=plt.rcParams['axes.prop_cycle'].by_key()['color'][2]) for i in range(len(plt.rcParams['axes.prop_cycle'])): xy=np.random.normal(size=2) ax4.add_patch(plt.Circle(xy,radius=0.3,color=plt.rcParams['axes.prop_cycle'].by_key()['color'][i])) ax4.axis('equal') plt.show()
plt.style.use('fivethirtyeight')
plt.style.use('dark_background')
plt.style.use('bmh')
plt.style.use('grayscale')
五、例子
1.画函数图
from matplotlib import pyplot as plt from matplotlib.patches import Polygon #画多边形的包 import numpy as np def func(x): return -(x-2)*(x-8)+40 x=np.linspace(0,10) y=func(x) fig,ax=plt.subplots() #首先把线画出来 plt.plot(x,y,'r',linewidth=2) a=2 b=9 ax.set_xticks([a,b])#横坐标只显示指定刻度值 ax.set_yticks([])#纵坐标不显示刻度 ax.set_xticklabels(['$a$','$b$'])#横坐标刻度显示指定名称,$将其换为公式格式 plt.figtext(0.9,0.05,'$x$')#在画布指定位置画出文字 plt.figtext(0.1,0.9,'$y$') #然后开始画积分部分的阴影 ix=np.linspace(a,b)#积分阴影部分的x轴范围 iy=func(ix) ixy=zip(ix,iy)#将x与y形成坐标对 verts=[(a,0)]+list(ixy)+[(b,0)]#多边形的各个点的坐标 poly=Polygon(verts,facecolor='0.9',edgecolor='0.5')#直接给数字就是赋予不同的灰度,数值越大越浅 ax.add_patch(poly) #画出数学公式 x_math=(a+b)*0.22 y_math=33 plt.text(x_math,y_math,r'$\int_a^b (-(x-2)*(x-8)+40)dx$',fontsize=14)#画出公式 plt.show()
2.画散点图和条形图
from matplotlib import pyplot as plt import numpy as np plt.style.use('ggplot') x=np.random.randn(200) y=x+np.random.randn(200)*0.5 margin_border=0.1 width=0.6 height=0.2 margin_between=0.02 height=0.2 #第一幅图的坐标 left_s=margin_border bottom_s=margin_border height_s=width widths_s=width #定义第二幅图 left_x=margin_border bottom_x=margin_border+width+margin_between height_x=height widths_x=width #定义第三幅图 left_y=margin_between+width+margin_border bottom_y=margin_border height_y=width widths_y=height #将三个图的底图画出来 plt.figure(1,figsize=(8,8))#定义一个正方形的画布 rect_s=[left_s,bottom_s,widths_s,height_s] rect_x=[left_x,bottom_x,widths_x,height_x] rect_y=[left_y,bottom_y,widths_y,height_y] axScatter=plt.axes(rect_s) axHisX=plt.axes(rect_x) axHisY=plt.axes(rect_y) #解决图与图之间坐标值文字重合的问题 axHisX.set_xticks([]) axHisY.set_yticks([]) #开始画图 axScatter.scatter(x,y,c='b') bin_width=0.25#条形宽度值设计 xymax=np.max([np.fabs(x),np.fabs(y)]) lim=np.ceil(xymax/bin_width)#求条形框的个数,有余数就加一 lim=lim*bin_width#设置合适的刻度值 axScatter.set_xlim(-lim,lim) axScatter.set_ylim(-lim,lim) bins=np.arange(-lim,lim+bin_width,bin_width) axHisX.hist(x,bins=bins,edgecolor='w')#设置直方图边缘为白色 axHisY.hist(y,bins=bins,orientation='horizontal',edgecolor='w')#使直方图旋转90度 axHisX.set_xlim(axScatter.get_xlim())#设置x轴范围,和点状图一样 axHisY.set_ylim(axScatter.get_ylim()) plt.title('Scatter and Hist') plt.show()
3.球员能力图
#_*_coding:utf-8 _*_ #在python中,要使用汉字,必须在首行加上这行字,且还要定义字体 from matplotlib import pyplot as plt from matplotlib.font_manager import FontProperties import numpy as np plt.style.use('ggplot') font=FontProperties(fname=r'C:\Windows\Fonts\STKAITI.TTF',size=12)#必须要定义字体,输入电脑系统字体的存储位置 ability_size=6 ability_label=[u'进攻',u'防守',u'盘带',u'速度',u'体力',u'射术']#u为强制转换符,使之可以用汉字显示 ax1=plt.subplot(221,projection='polar') ax2=plt.subplot(222,projection='polar') ax3=plt.subplot(223,projection='polar') ax4=plt.subplot(224,projection='polar') player={ 'M':np.random.randint(size=ability_size,low=60,high=99), 'H':np.random.randint(size=ability_size,low=60,high=99), 'P':np.random.randint(size=ability_size,low=60,high=99), 'Q':np.random.randint(size=ability_size,low=60,high=99) } theta=np.linspace(0,2*np.pi,6,endpoint=False) theta=np.append(theta,theta[0])#留个数据是有7个点的才能产生闭环,所以将第一个赋予最后一个 player['M']=np.append(player['M'],player['M'][0]) ax1.plot(theta,player['M'],'r') ax1.fill(theta,player['M'],'r',alpha=0.3)#图像填充 ax1.set_xticks(theta) ax1.set_xticklabels(ability_label,y=0.03,fontproperties=font)#文本到图像的距离,字体 ax1.set_title(u'梅西',position=(0.5,1),fontproperties=font,color='r',size=15) ax1.set_yticks([20,40,60,80,100]) player['H']=np.append(player['H'],player['H'][0]) ax2.plot(theta,player['H'],'g') ax2.fill(theta,player['H'],'g',alpha=0.3)#图像填充 ax2.set_xticks(theta) ax2.set_xticklabels(ability_label,y=0.03,fontproperties=font)#文本到图像的距离,字体 ax2.set_title(u'哈维',position=(0.5,1),fontproperties=font,color='g',size=15) ax2.set_yticks([20,40,60,80,100]) player['P']=np.append(player['P'],player['P'][0]) ax3.plot(theta,player['P'],'b') ax3.fill(theta,player['P'],'b',alpha=0.3)#图像填充 ax3.set_xticks(theta) ax3.set_xticklabels(ability_label,y=0.03,fontproperties=font)#文本到图像的距离,字体 ax3.set_title(u'皮克',position=(0.5,1),fontproperties=font,color='b',size=15)#调整title的位置 ax3.set_yticks([20,40,60,80,100]) player['Q']=np.append(player['Q'],player['Q'][0]) ax4.plot(theta,player['Q'],'y') ax4.fill(theta,player['Q'],'y',alpha=0.3)#图像填充 ax4.set_xticks(theta) ax4.set_xticklabels(ability_label,y=0.03,fontproperties=font)#文本到图像的距离,字体 ax4.set_title(u'切赫',position=(0.5,1),fontproperties=font,color='y',size=15) ax4.set_yticks([20,40,60,80,100]) #可以改成一个函数,调用四次 plt.show()