使用Python绘制图表大全总结
本篇文章主要介绍了使用python绘制图表大全总结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
在使用Python绘制图表前,我们需要先安装两个库文件numpy和matplotlib。
Numpy是Python开源的数值计算扩展,可用来存储和处理大型矩阵,比Python自身数据结构要高效;matplotlib是一个Python的图像框架,使用其绘制出来的图形效果和MATLAB下绘制的图形类似。
下面我通过一些简单的代码介绍如何使用 Python绘图。
一、图形绘制
立即学习“Python免费学习笔记(深入)”;
直方图
importmatplotlib.pyplotaspltimportnumpyasnpmu=100sigma=20x=mu+sigma*np.random.randn(20000)# 样本数量plt.hist(x,bins=100,color='green',normed=True)# bins显示有几个直方,normed是否对数据进行标准化plt.show()
条形图
importmatplotlib.pyplotaspltimportnumpyasnpy=[20,10,30,25,15]index=np.arange(5)plt.bar(left=index,height=y,color='green',width=0.5)plt.show()
折线图
importmatplotlib.pyplotaspltimportnumpyasnpx=np.linspace(-10,10,100)y=x**3plt.plot(x,y,linestyle='--',color='green',marker='<p></p><p>散点图</p><p class="jb51code"></p><pre class="brush:py;">importmatplotlib.pyplotaspltimportnumpyasnpx=np.random.randn(1000)y=x+np.random.randn(1000)*0.5plt.scatter(x,y,s=5,marker='<p></p><p>饼状图</p><p class="jb51code"></p><pre class="brush:py;">importmatplotlib.pyplotaspltimportnumpyasnplabels='A','B','C','D'fracs=[15,30,45,10]plt.axes(aspect=1)#使x y轴比例相同explode=[0,0.05,0,0]# 突出某一部分区域plt.pie(x=fracs,labels=labels,autopct='%.0f%%',explode=explode)#autopct显示百分比plt.show()
箱形图
主要用于显示数据的分散情况。图形分为上边缘、上四分位数、中位数、下四分位数、下边缘。外面的点时异常值
importmatplotlib.pyplotaspltimportnumpyasnpnp.random.seed(100)data=np.random.normal(size=(1000,4),loc=0,scale=1)labels=['A','B','C','D']plt.boxplot(data,labels=labels)plt.show()
二、图像的调整
1、23种点形状
"."point","pixel"o"circle"v"triangle_down"^"triangle_up""triangle_right"1"tri_down"2"tri_up"3"tri_left"4"tri_right"8"octagon"s"square"p"pentagon"*"star"h"hexagon1"H"hexagon2"+"plus"x"x"D"diamond"d"thin_diamond
2、8种內建默认颜色的缩写
b:blueg:greenr:redc:cyanm:magentay:yellowk:blackw:white
3、4种线性
- 实线 --虚线 -.点划线 :点线
4、一张图上绘制子图
importmatplotlib.pyplotaspltimportnumpyasnpx=np.arange(1,100)plt.subplot(221)#2行2列第1个图plt.plot(x,x)plt.subplot(222)plt.plot(x,-x)plt.subplot(223)plt.plot(x,x*x)plt.subplot(224)plt.plot(x,np.log(x))plt.show()
5、生成网格
importmatplotlib.pyplotaspltimportnumpyasnpy=np.arange(1,5)plt.plot(y,y*2)plt.grid(True,color='g',linestyle='--',linewidth='1')plt.show()
6、生成图例
importmatplotlib.pyplotaspltimportnumpyasnpx=np.arange(1,11,1)plt.plot(x,x*2)plt.plot(x,x*3)plt.plot(x,x*4)plt.legend(['Normal','Fast','Faster'])plt.show()