Numpy是Python开源的数值计算扩展,可用来存储和处理大型矩阵,比Python自身数据结构要高效;
matplotlib是一个Python的图像框架,使用其绘制出来的图形效果和MATLAB下绘制的图形类似。
在使用Python绘制图表前,我们需要先安装两个库文件numpy和matplotlib
pip install numpy
pip install matplotlib
import numpy as np
from pylab import *
num=100
sigma=20
x=num+sigma*np.random.randn(20000) #样本数量
plt.hist(x,bins=100,color="green",normed=True) #bins显示有几个直方,normed是否对数据进行标准化
plt.show() #显示图像
plt.savefig() #保存图片
运行结果:
import numpy as np
from pylab import *
value=[22,13,34]
index=["root","admin","lyshark"]
#index=np.arange(5)
plt.bar(left=index,height=value,color="green",width=0.5)
plt.show()
运行结果:
import numpy as np
from pylab import *
x=np.linspace(-10,10,100)
y=x**3
plt.plot(x,y,linestyle="--",color="green",marker="<")
plt.show()
运行结果:
import numpy as np
from pylab import *
x=np.random.randn(1000)
y=x+np.random.randn(1000)*0.5
plt.scatter(x,y,s=5,marker="<") #s表示面积 Marker表示图形
plt.show()
运行结果:
import numpy as np
from pylab import *
labels="cangjingkong","jizemingbu","boduoyejieyi","xiaozemaliya"
fracs=[45,10,30,15]
plt.axes(aspect=1)
explode=[0,0.05,0,0]
plt.pie(x=fracs,labels=labels,autopct="%0f%%",explode=explode)
plt.show()
运行结果:
主要用于显示数据的分散情况。图形分为上边缘、上四分位数、中位数、下四分位数、下边缘。外面的点时异常值
import numpy as np
from pylab import *
np.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()
运行结果:
import numpy as np
from pylab import *
x=np.arange(1,11,1)
plt.plot(x,x*2)
plt.plot(x,x*3)
plt.plot(x,x*4)
plt.legend(["BoDuoYeJieYi","CangJingKong","JiaTengYing"])
plt.show()
运行结果:
生成中文图片
import numpy as np
from pylab import *
mpl.rcParams['font.sans-serif'] = ['KaiTi']
label = "windows xp","windows 7","Windows 8","Linux 4","Centos 6","Huawei交换机"
fracs = [1,2,3,4,5,1]
plt.axes(aspect=1)
plt.pie(x=fracs,labels=label,autopct="%0d%%")
plt.show()