当前位置: 首页 > 后端技术 > Python

用于Python数据可视化的matplotlib

时间:2023-03-26 19:03:28 Python

1.导入常用模块importnumpyasnpimportmatplotlibimportmatplotlib.mlabasmlabimportmatplotlib.pyplotaspltimportmatplotlib.font_managerasfmfrommpl_toolkits.mplot3dimportAxes3D2.解决中文乱码显示异常问题myfont=fm.FontProperties(fname="fontfilepath")负号显示为正方形matplotlib.rcParams['axes.unicode_minus']=False3.折线图生成的数据x=np.linspace(-np.pi,np.pi,256,endpoint=True)#从-π等间隔取256个点到πy_cos,y_sin=np.cos(x),np.sin(x)#对应x的cos和sin值来初始化画布plt.figure(figsize=(8,6),dpi=80)#figsize定义画布的大小,dpi定义画布的分辨率plt.title("Simplelinechart",fontproperties=myfont)#设置标题,中文需要指定字体plt.grid(True)#是否显示网格设置坐标轴#设置X轴plt.xlabel("X轴",fontproperties=myfont)#axislabelplt.xlim(-4.0,4.0)#axisrangeplt.xticks(np.linspace(-4,4,9,endpoint=True))#AxisScale#设置Y轴plt.ylabel("Y轴",fontproperties=myfont)plt.ylim(-1.0,1.0)plt.yticks(np.linspace(-1,1,9,endpoint=True))绘制数据线有几种类型:"g+-","r*-","b.-","yo-",第一个字符代表颜色,第二个字符代表节点样式,第三个字符代表连线样式plt.plot(x,y_cos,"b--",linewidth=2.0,label="cosexample")#前两个参数为坐标值,第三个参数为线型,linewidth为线宽,label为图例文字plt.plot(x,y_sin,"g-",linewidth=2.0,label="sinexample")设置图例plt.legend(loc="upperleft",prop=myfont,shadow=True)#loc可以是上、下和左、右、中心图形显示的组合plt.show()面积图plt.fill_between(x,-1,y_sin,where=True,color="blue",alpha=0.25)plt.show()三维折线图#生成测试数据x=np.linspace(0,1,1000)y=np.linspace(0,1,1000)z=np.sin(x*2*np.pi)/(y+0.1)#生成画布(两种形式)fig=plt.figure()ax=fig.gca(projection="3d",title="plottitle")#ax=fig.add_subplot(111,projection="3d",title="plottitle")#绘制三维折线图ax.plot(x,y,z,color="red",linestyle="-")#设置坐标轴图标ax.set_xlabel("XLabel")ax.set_ylabel("YLabel")ax.set_zlabel("ZLabel")#图形显示plt.show()4.直方图生成数据#生成测试数据means_men=np.array((20,35,30,35,27))means_women=np.array((25,32,34,20,25))初始化画布plt.figure(figsize=(8,6),dpi=80)#figsize定义画布大小,dpi定义画布分辨率plt.title("Simplehistogram",fontproperties=myfont)#设置标题,中文需要指定字体plt.grid(True)#是否显示网格设置轴index=np.arange(len(means_men))[0,1,2,3,4]bar_height=0.35#列宽plt.xlim(0,45)#轴范围plt.xlabel("Scores")#轴标签plt.ylabel("Group")plt.yticks(index+(bar_height/2),("A","B","C","D","E"))#轴刻度绘制数据#绘制水平直方图plt.barh(index,means_men,height=bar_height,alpha=0.2,color="b",label="Men")plt.barh(index+bar_height,means_women,height=bar_height,alpha=0.8,color="r",label="女性")设置图例plt.legend(loc="upperright",shadow=True)在zip(index,means_men)中显示i,v的数据值:plt.text(v+0.3,i,v,ha="left",va="center")fori,vinzip(index,means_women):plt.text(v+0.3,i+bar_height,v,ha="left",va="center")图形显示plt.show()设置竖直柱形图的坐标轴,交换x和yindex=np.arange(len(means_men))[0,1,2,3,4]bar_height=0.35#列宽plt.ylim(0,45)plt.ylabel("Scores")plt.xlabel("Group")plt.xticks(index+(bar_height/2),("A","B","C","D","E"))绘制数据#绘制垂直直方图plt.bar(index-bar_height/2,means_men,width=bar_height,alpha=0.4,color="b",label="Men")plt.bar(index+bar_height/2、means_women,width=bar_height,alpha=0.4,color="r",label="Women")图形显示plt.show()堆叠直方图#生成测试数据data=np.array([[1,4,2,5,2],[2,1,1,3,6],[5,3,6,4,1]])#设置标题plt.title("hierarchicalhistogram",fontproperties=myfont)#设置相关参数index=np.arange(len(data[0]))color_index=["r","g","b"]#声明底部位置bottom=np.array([0,0,0,0,0])#一张一张画图,并更新iinrange(len(data))的底部位置:plt.bar(index,data[i],width=0.5,color=color_index[i],bottom=bottom,alpha=0.7,label="label%d"%i)bottom+=data[i]#设置图例位置plt.legend(loc="upperleft",prop=myfont,shadow=True)#图形显示plt.show()histogramFigure#生成测试数据mu,sigma=100,15x=mu+sigma*np.random.randn(10000)#设置标题plt.title("Histogram",fontproperties=myfont)#绘制直方图并返回相关结果n,bins,patches=plt.hist(x,bins=50,density=1,cumulative=False,color="green",alpha=0.6,label="histogram")##根据直方图返回的结果,绘制折线图y=mlab.normpdf(bins,mu,sigma)plt.plot(bins,y,"r--",label="line")#设置图例位置plt.legend(loc="upperleft",prop=myfont,shadow=True)#图形显示plt.show()三维直方图#生成测试数据(位置数据)xpos=[1,2,3,4,5,6,7,8,9,10]ypos=[2,3,4,5,1,6,2,1,7,2]zpos=[0,0,0,0,0,0,0,0,0,0]#生成测试数据(列参数)dx=[1,1,1,1,1,1,1,1,1,1]dy=[1,1,1,1,1,1,1,1,1,1]dz=[1,2,3,4,5,6,7,8,9,10]#生成画布(两种形式)fig=plt.figure()ax=fig.gca(projection="3d",title="plottitle")#设置坐标轴图标ax.set_xlabel("XLabel")ax.set_ylabel("YLabel")ax.set_zlabel("ZLabel")#绘制三维直方图ax.bar3d(xpos,ypos,zpos,dx,dy,dz,alpha=0.5)#图形显示plt.show()5.饼图生成数据#生成测试数据sizes=[15,30,45,10]#valuelabels=["Frogs","Chinese","Dogs","Logs"]#labelcolors=["yellowgreen","gold","lightskyblue","lightcoral"]#颜色初始化画布plt.figure(figsize=(8,6),dpi=80)#figsize定义画布size,dpi定义画布分辨率plt.title("simplepiechart",fontproperties=myfont)#设置标题,中文需要指定字体设置扇区偏差值explode=[0,0.05,0,0]绘制数据块,l_text,p_text=plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct="%1.1f%%",shadow=True,startangle=90)#autopct设置显示百分比的格式,startangle为l_text中的文字设置图片旋转方向:text.set_fontproperties(myfont)#设置字体避免中文乱码图形显示plt.show()六、散点图生成数据N=1000x=np。随机的。randn(N)y=x+np.random.randn(N)*0.5初始化画布plt.figure(figsize=(8,6),dpi=80)#figsize定义画布尺寸,dpi定义画布分辨率plt.title("简单散点图",fontproperties=myfont)#设置标题,中文需要指定绘制数据的字体plt.scatter(x,y,s=5,c="red",marker="o")#s表示点的大小,c表示点的颜色,marker表示点的形状图形显示plt.show()3D散点图#生成测试数据x=np.random.random(100)y=np.random.random(100)z=np.random.random(100)color=np.random.random(100)scale=np.random.random(100)*100#生成画布(两种形式)fig=plt.figure()fig.suptitle("3D散点图",fontproperties=myfont)ax=fig.add_subplot(111,projection="3d")#设置坐标轴图标ax.set_xlabel("XLabel")ax.set_ylabel("YLabel")ax.set_zlabel("ZLabel")#设置坐标轴范围ax.set_xlim(0,1)ax.set_ylim(0,1)ax.set_zlim(0,1)#画一个日ree维散点图ax.scatter(x,y,z,s=scale,c=color,marker=".")#图形化展示plt.show()七、雷达图生成数据labels=np.array([“A组”、“B组”、“C组”、“D组”、“E组”、“F组”])data=np.array([68,83,90,77,89,73])theta=np.linspace(0,2*np.pi,len(data),endpoint=False)#每个维度的角度值初始化画布plt.subplot(111,polar=True)#3个数字,前两位表示画布分为多少行多少列,最后一位表示花放的位置plt.title("雷达图",fontproperties=myfont)set坐标轴plt。ylim(0,100)#坐标轴范围绘图数据plt.thetagrids(theta*(180/np.pi),labels=labels,fontproperties=myfont)图形显示plt.show()想了解更多编程开发,联系和我一起成长进步,请关注我的公众号“松果仓库”,分享书呆子&程序员的各种资源,谢谢!!!