一、numpy库的常用语句
import numpy as npx = np.random.randint(1, 100, 20)np.savetxt(\'x.yui\', x, fmt=\'%d\', delimiter=\',\')y = np.loadtxt(\'x.yui\', delimiter=\',\')y.sort()y.max()y.min()y.mean()y.var()
二、散点图
import matplotlib.pyplot as pltimport numpy as npN = 1000x = np.random.randn(N)y = np.random.randn(N)plt.scatter(x, y, s=50, c=\'r\', alpha=0.7, marker=\'1\')#s为点的面积大小,c为颜色,alpha为透明度,marker为点的形状N = 1000x = np.random.randn(N)y = x+np.random.randn(N)*0.3plt.scatter(x, y, s=50, c=\'xkcd:sky blue\', alpha=0.7, marker=\'*\')
三、折线图
import matplotlib.pyplot as pltimport numpy as npimport matplotlib.dates as mdatesx = np.linspace(-10,10,5)#-10到10的100个等差数列y = x**2plt.plot(x, y)plt.show()##############下面读入股票数据画图####################def convert_date(date_bytes):return mdates.strpdate2num(\' %Y/%m/%d\')(date_bytes.decode(\'ascii\'))#########%Y前有个空格,因为文档中存在空格,如果没空格会报错,所以要仔细查看文档日期date, high, low = np.loadtxt(\'C:/Users/Administrator/Desktop/300411.csv\', delimiter=\',\', converters={0: convert_date},skiprows=2, usecols=(0, 2, 3), unpack=True)plt.plot_date(date, high, \'-\', c=\'r\')##横坐标为日期的特殊画图函数plt.plot_date(date, low, linestyle=\'--\', c=\'g\',marker=\'*\')plt.show()
四、条形图
import matplotlib.pyplot as pltimport numpy as npN = 5y =[20, 10, 30, 25, 15]index = np.arange(N)pl = plt.bar(x=index, height=y,align=\'edge\', color=\'red\',width=0.5)##水平条形图,有些参数不同于上个函数plh = plt.barh(y=index, width=y, align=\'center\', color=\'blue\',height=0.5)plt.show()############对比图#########index=np.arange(4)sales_BJ = [52,56,78,57]sales_SH = [67,89,75,45]bar_width=0.4plt.bar(index, sales_BJ, bar_width, align=\'edge\', color=\'b\')plt.bar(index+bar_width,sales_SH,bar_width, align=\'edge\', color=\'r\')plt.show()plt.barh(y=index, width=sales_BJ,height= bar_width, align=\'edge\', color=\'b\')plt.barh(y=index+bar_width,width=sales_SH, height=bar_width, align=\'edge\', color=\'r\')plt.show()###########层叠图plt.bar(index,sales_BJ, bar_width, align=\'edge\', color=\'b\')plt.bar(index,sales_SH, bar_width,color=\'r\', align=\'edge\', bottom=sales_BJ)##注意bottom的使用plt.show()###########层叠图plt.barh(index,sales_BJ, bar_width, align=\'edge\', color=\'b\')plt.barh(index,width=sales_SH,height= bar_width,color=\'r\', align=\'edge\',left=sales_BJ)####注意left的使用plt.show()
五、直方图
表示数据分布
###########直方图##########import matplotlib.pyplot as pltimport numpy as npmu = 100 #均值sigma = 20 #标准差x = mu + sigma * np.random.randn(2000)plt.hist(x, bins=10, color=\'r\', normed= True)###因为标准化了,图像纵坐标是在x轴范围内的频率plt.hist(x, bins=50, color=\'g\', normed= False)plt.show()####未标准化,纵轴是范围内出现的数据个数#####双变量直方图#########探索双变量的联合分布很有用x = np.random.randn(1000)+2y = np.random.randn(1000)+3plt.hist2d(x,y,bins=50)##颜色的深浅表示频率的大小,中间亮,频率高
六、饼状图
#########################饼状图###################import matplotlib.pyplot as pltlabels = \'A\', \'B\', \'C\', \'D\'fracs = [15,30,45,10]explode=[0.3,0,0,0]###定义块离圆心距离,突出某块plt.pie(x=fracs, labels=labels, autopct=\'%.0f%%\', explode=explode,shadow=True)#autopct设定显示每块的百分比,shadow显示阴影plt.show()
七、箱线图
显示数据分散情况
上边缘,上四分位数,中位数,下四分位数,下边缘,异常值
import matplotlib.pyplot as pltimport numpy as npnp.random.seed(100)data = np.random.normal(size=1000, loc=0, scale=1)plt.boxplot(data,sym=\'o\', whis=1.5)plt.boxplot(data,sym=\'o\',whis=90000)###sym改变异常点形状,whis改变线的长短来显示隐藏异常点plt.show()####多个箱线图对比####data1 = np.random.normal(size=(1000,4), loc=0, scale=1)labels=[\'A\',\'B\',\'C\',\'D\']plt.boxplot(data1,labels=labels)plt.show()##更多的见matplotlib网站demo
八、颜色与样式
#########################颜色与样式#################8种默认颜色缩写,b,g,r,c,m,y,k,w###灰色阴影###html 十六进制###RGB 元组import matplotlib.pyplot as pltimport numpy as npy = np.arange(1, 5)plt.plot(y, color=\'k\')plt.plot(y+1, color=\'0.5\')##灰度plt.plot(y-1, color=\'#FF00FF\')###十六颜色代码plt.plot(y+2, color=(0.1, 0.2,0.5))##括号RGBplt.show()##########点样式##plt.plot(y, marker=\'o\')###有marker的会有过点直线plt.plot(y+1, \'^\')###下面的都没有线,且形状不同,默认颜色也不同plt.plot(y-1, \'p\')plt.plot(y+2, \'.\')plt.show()#####线样式######实线-,虚线--,点划线-.,点线:plt.plot(y, \'--\')###虚线plt.plot(y+1, \'-.\')###点划线plt.plot(y-1, \':\')##点线plt.plot(y+2, \'-\')##实线plt.show()#######样式字符串####颜色+点型+线型,一起定义plt.plot(y, \'cx--\')###plt.plot(y+1, \'kp-.\')###黑色五角点划线plt.plot(y-1, \'mo:\')##紫色圆点线plt.plot(y+2, \'y^-\')##黄色三角实线plt.show()
九、面向对象
#########################面向对象#################pyplot###pylab,模拟matlab环境,不推荐###面向对象的方式,精髓import matplotlib.pyplot as pltimport numpy as np#####pyplotx = np.arange(0, 10,1)y = np.random.randn(len(x))plt.plot(x, y)plt.title(\'pyplot\')plt.show()###面向对象fig = plt.figure()ax = fig.add_subplot(111)l,=plt.plot(x, y)t = ax.set_title(\'object oriented\')
十、子图
#########################子图#################对象:FiguCanvas, Figure, Axes###ax = fig.add.subplot(111), 参数一二三:子图总行数,总列数,子图位置###import matplotlib.pyplot as pltimport numpy as np###面向对象x = np.arange(1, 100)fig = plt.figure()ax1 = fig.add_subplot(221)ax1.plot(x, x)ax2 = fig.add_subplot(222)ax2.plot(x, -x)ax3 = fig.add_subplot(223)ax3.plot(x, x*x)ax4 = fig.add_subplot(224)ax4.plot(x, np.log(x))####pyplotplt.subplot(221)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))
十一、多图
########################多图#################对象:FiguCanvas, Figure, Axes###创建多个figureimport matplotlib.pyplot as pltfig1=plt.figure()ax1=fig1.add_subplot(111)ax1.plot([1,2,3],[3,2,1])fig2=plt.figure()ax2=fig2.add_subplot(111)ax2.plot([1,2,3],[1,2,3])plt.show()
十二、网格
#########################网格#################plt###面向对象import matplotlib.pyplot as pltimport numpy as np####plt,有交互效果,可不断变更图中网格设定y = np.arange(1,5)plt.plot(y,y*2)plt.grid(True)#打开网格plt.grid()#关闭网格plt.grid(color=\'r\',linewidth=\'2\',linestyle=\'--\')plt.grid(color=\'g\')###面向对象,没有交互效果x = np.arange(0, 10, 1)fig = plt.figure()ax = fig.add_subplot(111)plt.plot(x, x*2)ax.grid(color=\'g\', linestyle=\'--\')plt.show()
十三、图例
########################图例#################plt###面向对象import matplotlib.pyplot as pltimport numpy as np####plt,有交互效果,可不断变更图中网格设定x = np.arange(1,11,1)plt.plot(x,x*2,label=\'Normal\')plt.plot(x,x*3,label=\'Fast\')plt.plot(x,x*4,label=\' Faster\')plt.show()##没有图例plt.legend()##出现图例plt.legend(loc=1)###loc设定图例位置0~10plt.legend(ncol=3)###图例分为几列,使图例合理###面向对象,没有交互效果fig = plt.figure()ax = fig.add_subplot(111)line,= plt.plot(x, x, label=\'Inline label\')plt.show()##没有图例ax.legend()##出现图例#####或者不在plot里设label####line.set_label(\'Label via method\')ax.legend()
十四、坐标轴范围
#######################坐标轴范围##############import matplotlib.pyplot as pltimport numpy as np####plt,有交互效果,可不断变更图中网格设定x = np.arange(-10,11,1)plt.plot(x,x*x)plt.show()plt.axis([-5,5,1,30])###设定x坐标轴在-5~5,y轴1~30##也可如下设定plt.xlim([-6,6])###只调整x轴plt.ylim([0,35])###只调整y轴##只调整一边plt.plot(x,x*x)plt.show()plt.xlim(xmin=-5)plt.xlim(xmax=8)
十五、坐标轴刻度
#######################坐标轴刻度#################plt###面向对象import matplotlib.pyplot as pltimport numpy as npimport datetimeimport matplotlib as mpl####面向对象,无交互效果x = np.arange(1,11,1)plt.plot(x, x)##二维的列表ax = plt.gca()##获取当前axis,get current axisax.locator_params(nbins=20)##both分20个ax.locator_params(\'x\',nbins=10)##只调整x轴ax.locator_params(\'y\',nbins=5)##只调整y轴plt.show()######plt,交互的plt.locator_params(\'y\',nbins=10)#####日期坐标调整########面向对象fig = plt.figure()start = datetime.datetime(2015,1,1)stop = datetime.datetime(2016,1,1)delta = datetime.timedelta(days=1)dates = mpl.dates.drange(start,stop,delta)#####生成一年的顺序datesy = np.random.randn(len(dates))ax = plt.gca()ax.plot_date(dates,y,linestyle=\'-\',marker=\'\')plt.show()#####自行设置横坐标轴的时间格式###date_format = mpl.dates.DateFormatter(\'%Y-%m-%d\')ax.xaxis.set_major_formatter(date_format)fig.autofmt_xdate()#####防止时间刻度重叠,斜着显示
十六、添加坐标轴
#######################添加坐标轴#################同一幅图,两条线的刻度不同,需要双坐标轴import matplotlib.pyplot as pltimport numpy as npx = np.arange(2,20,1)y1 = x*xy2 = np.log(x)######plt,交互的plt.plot(x, y1)plt.show()plt.twinx()###第二条y坐标轴,twinx,双胞胎xplt.plot(x, y2,\'r\')###在新坐标轴刻度下的第二条线####面向对象,无交互效果fig = plt.figure()ax1 = fig.add_subplot(111)ax1.plot(x, y1)ax1.set_ylabel(\'Y1\')ax2 = ax1.twinx()ax2.plot(x, y2,\'r\')ax2.set_ylabel(\'Y2\')ax1.set_xlabel(\'Compare Y1 and Y2\')####twiny,两个x轴plt.plot(y1, x)plt.twiny()plt.plot(y2, x, \'r\')plt.show()
十七、注释
#######################注释#################着重提示import matplotlib.pyplot as pltimport numpy as npx = np.arange(-10,11,1)y = x*x######plt,交互的plt.plot(x, y)plt.annotate(\'This is the bottom\',xy=(0,5),xytext=(0,20),arrowprops=dict(facecolor=\'r\', headlength=5, headwidth=15, width=10))###xy是箭头起始点,xytext是文本起始点,facecolor图形颜色,headlength箭头长度,headwidth箭头宽度,width枝干宽度plt.show()
十八、文字
#######################文字#################只有纯文字标注import matplotlib.pyplot as pltimport numpy as npx = np.arange(-10,11,1)y = x*x######plt,交互的plt.plot(x, y)plt.show()plt.text(-2, 40, \'function:y=x*x\', family=\'serif\',size=20,color=\'r\',style=\'italic\',weight=\'regular\')#family是字体设定plt.text(-2, 20, \'function:y=x*x\', family=\'fantasy\', size=20,color=\'g\',style=\'normal\',weight=\'bold\', bbox=dict(facecolor=\'r\',alpha=0.3))#style是italic/normal###weight设定字体粗细,可以用数字,也可用type###bbox给文本加个框,可对框设定很多
十九、Tex公式
#######################Tex公式#################数学公式,自带mathtext引擎###以$符号为公式开始和结束符,自动识别,$x*x+z$###官网介绍的很详细,对各种数学符号的输入import matplotlib.pyplot as pltimport numpy as npfig = plt.figure()ax = fig.add_subplot()ax.set_xlim([1,7])ax.set_ylim([1,5])ax.text(2,4,r\"$ \\alpha_i \\beta_i \\pi \\lambda \\omega $\", size=25)##r表示字符串不转义ax.text(4,4,r\"$ \\sin(0)=\\cos(\\frac{\\pi}{2}) $\", size=25)plt.show()
二十、工具栏
#######################工具栏#################对于密集图片如何观察###图片视图工具栏如何使用import matplotlib.pyplot as pltimport numpy as npN = 1000x = np.random.randn(N)y = np.random.randn(N)colors = np.random.rand(N)area = np.pi*(15*np.random.randn(N))**2plt.scatter(x, y, s=area, c=colors, alpha = 0.5)plt.show()
二十一、区域填充,上色
#######################区域填充,上色#################fill,fill_between函数import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0,5*np.pi,1000)y1 = np.sin(x)y2 = np.sin(2*x)plt.fill(x,y1, \'b\',alpha=0.3)###填充函数与x坐标轴间的区域plt.fill(x,y2,\'r\',alpha=0.3)plt.show()#####面向对象,填充任意两条线的区域###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\',alpha=0.5)##分区域填充不同颜色ax.fill_between(x,y1,y2,where=y1<=y2,facecolor=\'g\',alpha=0.5)plt.show()########当x很离散时,填充的区域会出现部分空白,加入interpolate###x1 = np.linspace(0,5*np.pi,100)y11 = np.sin(x1)y12 = np.sin(2*x1)fig1 = plt.figure()ax1 = plt.gca()ax1.plot(x1,y11,color=\'r\')ax1.plot(x1,y12,color=\'b\')ax1.fill_between(x1,y11,y12,where=y11>y12,facecolor=\'y\',alpha=0.5,interpolate=True)ax1.fill_between(x1,y11,y12,where=y11<=y12,facecolor=\'g\',alpha=0.5,interpolate=True)plt.show()
二十二、形状填充,画图样式
#######################形状填充,画图样式#################patches类###add_patchimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.patches as mpatches###改变绘图样式,美化,plt.style###可在控制台输入print(plt.style.available),查看多种样式plt.style.use(\'ggplot\')###fivethirtyeightfig, 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 = mpatches.Circle(xy1,0.05)####圆:半径ax.add_patch(circle)rect = mpatches.Rectangle(xy2,0.2,0.1,color=\'r\')###长方形:宽,高ax.add_patch(rect)polygon = mpatches.RegularPolygon(xy3,5,0.1,color=\'g\')##正多边形:第一个参数是边数ax.add_patch(polygon)ellipse = mpatches.Ellipse(xy4,0.4,0.2,color=\'y\')##椭圆:长轴,短轴ax.add_patch(ellipse)plt.axis(\'equal\')###使坐标轴1:1plt.grid()###网格plt.show()
二十三、极坐标绘图
#######################极坐标绘图#################点所在位置的半径,角度###以点按顺序画线import matplotlib.pyplot as pltimport numpy as npplt.style.use(\'ggplot\')r1 = np.arange(1,6,1)r2 = np.empty(5)r2.fill(5)r3=np.empty(9)r3.fill(5)pi = np.pitheta1 = [0, pi/2, pi, 3*pi/2, 2*pi]theta2 = [0,pi/4,pi/2,3*pi/4,pi,5*pi/4,6*pi/4,7*pi/4,8*pi/4]ax = plt.subplot(111, projection=\'polar\')ax.plot(theta1,r1,color=\'r\',linewidth=3)ax.plot(theta1,r2,color=\'g\',linewidth=3)ax.plot(theta2,r3,color=\'m\',linewidth=3)ax.grid(True)plt.show()