import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2*np.pi,500)
y = np.sin(x)
plt.fill(x,y,color="cornflowerblue",alpha=0.4)
plt.plot(x,y,color="cornflowerblue",alpha=0.4)
plt.plot([x[0],x[-1]],[y[0],y[-1]],color="cornflowerblue",alpha=0.8)
plt.xlim(0,2*np.pi)
plt.ylim(-1.1,1.1)
plt.show()
1.2 交叉曲线的颜色填充
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2,500)
y1 = np.sin(2*np.pi*x)
y2 =1.1*np.sin(3*np.pi*x)
fig,ax = plt.subplots(3,1,sharex="all")#获得一个画布对象fig,和一个坐标轴列表ax
ax[0].fill_between(x,0,y2,alpha=0.5)
ax[0].set_ylim(-1.2,1.2)
ax[1].fill_between(x,y2,1.1,alpha=0.5)
ax[1].set_ylim(-1.2,1.2)
ax[2].fill_between(x,y1,y2,alpha=0.5)
ax[2].set_xlim(0,2)
ax[2].set_ylim(-1.2,1.2)
plt.show()
1.3 水平方向的交叉曲线的颜色填充
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2,500)
y1 = np.sin(2*np.pi*x)
y2 =1.1*np.sin(3*np.pi*x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y1,color="k",lw=1,ls="-")
ax.plot(x,y2,color="k",lw=1,ls="-")
ax.fill_between(x,y1,y2,where=y2>y1,interpolate=True,facecolor="cornflowerblue",alpha=0.7)
ax.fill_between(x,y1,y2,where=y1>y2,interpolate=True,facecolor="darkred",alpha=0.7)
ax.set_xlim(0,2)
ax.set_ylim(-1.2,1.2)
ax.grid(ls=":",lw=1,color="gray",alpha=0.5)
plt.show()
1.4 垂直方向的交叉曲线的颜色填充
import matplotlib.pyplot as plt
import numpy as np
y = np.linspace(0,2,500)
x1 = np.sin(2*np.pi*y)
x2 =1.1*np.sin(3*np.pi*y)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x1,y,color="k",lw=1,ls="-")
ax.plot(x2,y,color="k",lw=1,ls="-")
ax.fill_betweenx(y,x1,x2,where=x2>x1,interpolate=True,facecolor="cornflowerblue",alpha=0.7)
ax.fill_betweenx(y,x1,x2,where=x2<x1,interpolate=True,facecolor="darkred",alpha=0.7)
ax.set_xlim(-1.2,1.2)
ax.set_ylim(0,2)
ax.grid(ls=":",lw=1,color="gray",alpha=0.5)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
fig,ax = plt.subplots(1,2,subplot_kw={"aspect":"equal"})# subplot(121)
angles = np.linspace(0,135,4)
ellipse =[Ellipse((2,2),4,2,a)for a in angles]for elle in ellipse:
ax[0].add_patch(elle)
elle.set_alpha(0.4)
elle.set_color("cornflowerblue")
ax[0].axis([-1,5,-1,5])# subplot(122)
num = np.arange(0,100,1)#np.random.rand(n,m)就是产生[n,m]个0-1的数字
ellipse =[Ellipse(xy=np.random.rand(2)*10,
width=np.random.rand(1),
height=np.random.rand(1),
angle=np.random.rand(1)*360)for i in num]for elle in ellipse:
ax[1].add_patch(elle)
elle.set_alpha(np.random.rand(1))
elle.set_color(np.random.rand(3))#生成一个rgb三元数组
ax[1].axis([-1,11,-1,11])
plt.tight_layout()
plt.show()
2.3矩形
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
fig,ax = plt.subplots(subplot_kw={"aspect":"equal"})
x1 = np.arange(1,2.6,0.1)
y1 = x1+2
x2 = np.arange(2.5,4.1,0.1)
y2 =-x2+7# set background color
rectangle = ax.patch
rectangle.set_facecolor("lightskyblue")# house
rectangle1 = Rectangle((1,0),3,3,facecolor="w",edgecolor="rosybrown")# door
rectangle2 = Rectangle((1.5,0),1,1.5,facecolor="w",edgecolor="rosybrown",hatch="|||")# window
rectangle3 = Rectangle((2.9,1.7),0.6,0.6,facecolor="w",edgecolor="rosybrown")
rectangle_list =[rectangle1,rectangle2,rectangle3]# roof line
ax.plot([1,2.5,4],[3,4.5,3],color="rosybrown")# window line
ax.plot([3.2,3.2],[1.7,2.3],color="rosybrown")
ax.plot([2.9,3.5],[2.0,2.0],color="rosybrown")# roof filled color
ax.fill_between(x1,3,y1,color="w",interpolate=True)
ax.fill_between(x2,3,y2,color="w",interpolate=True)for rect in rectangle_list:
ax.add_patch(rect)
ax.axis([0,5,0,6])
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Shadow,Wedge
fig,ax = plt.subplots(subplot_kw={"aspect":"equal"})
font_style ={"family":"serif","size":12,"style":"italic","weight":"black"}
sample_data =[350,150,200,300]
total =sum(sample_data)
percents =[i/float(total)for i in sample_data]
angles =[360*i for i in percents]
delta =45
wedge1 = Wedge((2,2),1,delta,delta+sum(angles[0:1]),color="orange")
wedge2 = Wedge((2,1.9),1,delta+sum(angles[0:1]),delta+sum(angles[0:2]),facecolor="steelblue",edgecolor="white")
wedge3 = Wedge((2,1.9),1,delta+sum(angles[0:2]),delta+sum(angles[0:3]),facecolor="darkred",edgecolor="white")
wedge4 = Wedge((2,1.9),1,delta+sum(angles[0:3]),delta,facecolor="lightgreen",edgecolor="white")
wedges =[wedge1,wedge2,wedge3,wedge4]for wedge in wedges:
ax.add_patch(wedge)
ax.text(1.7,2.5,"%3.1f%%"%(percents[0]*100),**font_style)
ax.text(1.2,1.7,"%3.1f%%"%(percents[1]*100),**font_style)
ax.text(1.7,1.2,"%3.1f%%"%(percents[2]*100),**font_style)
ax.text(2.5,1.7,"%3.1f%%"%(percents[3]*100),**font_style)
ax.axis([0,4,0,4])
plt.show()
2.8 圆环图
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle,Shadow,Wedge
fig,ax = plt.subplots(subplot_kw={"aspect":"equal"})
font_style ={"family":"serif","size":12,"style":"italic","weight":"black"}
sample_data =[350,150,200,300]
total =sum(sample_data)
percents =[i/float(total)for i in sample_data]
angles =[360*i for i in percents]
delta =45
wedge1 = Wedge((2,1.9),1,delta,delta+sum(angles[0:1]),facecolor="orange",edgecolor="white",width=0.3)
wedge2 = Wedge((2,1.9),1,delta+sum(angles[0:1]),delta+sum(angles[0:2]),facecolor="steelblue",edgecolor="white",width=0.3)
wedge3 = Wedge((2,1.9),1,delta+sum(angles[0:2]),delta+sum(angles[0:3]),facecolor="darkred",edgecolor="white",width=0.3)
wedge4 = Wedge((2,1.9),1,delta+sum(angles[0:3]),delta,facecolor="lightgreen",edgecolor="white",width=0.3)
rectangle = Rectangle((3.0,0.0),1.3,1.3,facecolor="w",edgecolor="rosybrown")
rectangle1 = Rectangle((3.2,0.1),0.3,0.2,color="orange")
rectangle2 = Rectangle((3.2,0.4),0.3,0.2,color="steelblue")
rectangle3 = Rectangle((3.2,0.7),0.3,0.2,color="darkred")
rectangle4 = Rectangle((3.2,1.0),0.3,0.2,color="lightgreen")
wedges =[wedge1,wedge2,wedge3,wedge4,rectangle,rectangle1,rectangle2,rectangle3,rectangle4]for wedge in wedges:
ax.add_patch(wedge)
ax.text(3.6,0.1,"%3.1f%%"%(percents[0]*100),**font_style)
ax.text(3.6,0.4,"%3.1f%%"%(percents[1]*100),**font_style)
ax.text(3.6,0.7,"%3.1f%%"%(percents[2]*100),**font_style)
ax.text(3.6,1.0,"%3.1f%%"%(percents[3]*100),**font_style)
ax.axis([0,4.5,-0.5,4])
plt.show()
3. 组合展示统计图形
3.1 判别分析示意图
import matplotlib.pyplot as plt
import numpy as np
fig,ax = plt.subplots()
num =50# new sample
sample =10*np.random.rand(num,2)
var1 = sample[:,0]
var2 = sample[:,1]# threshold value
td =12# discriminant function
df =2*var1+var2
cates11 = np.ma.masked_where(df>=td,var1)
cates12 = np.ma.masked_where(df>=td,var2)
cates21 = np.ma.masked_where(df<=td,var1)
cates22 = np.ma.masked_where(df<=td,var2)
ax.scatter(var1,var2,s=cates11*50,marker="s",c=cates11)
ax.scatter(var1,var2,s=cates21*50,marker="o",c=cates21)
ax.plot(var1,-2*var1+12,lw=1,color="b",alpha=0.65)
ax.axis([-1,11,-1,11])
plt.show()
3.2 日期型时间序列图
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
fig,ax = plt.subplots()
months = mdates.MonthLocator()# a Locator instance
dateFmt = mdates.DateFormatter("%m/%d/%y")# a Formatter instance# format the ticks
ax.xaxis.set_major_formatter(dateFmt)
ax.xaxis.set_minor_locator(months)# set appearance parameters for ticks,ticklabels,and gridlines
ax.tick_params(axis="both",direction="out",labelsize=10)
date1 = datetime.date(2008,4,17)
date2 = datetime.date(2017,5,4)
delta = datetime.timedelta(days=5)
dates = mdates.drange(date1, date2, delta)
y = np.random.normal(100,15,len(dates))
ax.plot_date(dates,y,"b-",alpha=0.7)
fig.autofmt_xdate()
plt.show()
3.3 向直方图中添加概率密度曲线
# -*- coding:utf-8 -*-import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
#设置中文字体类型是仿宋
mpl.rcParams["font.sans-serif"]=["FangSong"]
mpl.rcParams["axes.unicode_minus"]=False
mu =60.0
sigma =2.0
x = mu+sigma*np.random.randn(500)
bins =50
fig,ax = plt.subplots(1,1)
n,bins,patches = ax.hist(x,
bins,
normed=True,
histtype="bar",
facecolor="cornflowerblue",
edgecolor="white",
alpha=0.75)
y =((1/(np.power(2*np.pi,0.5)*sigma))*
np.exp(-0.5*np.power((bins-mu)/sigma,2)))
ax.plot(bins,y,color="orange",ls="--",lw=2)
ax.grid(ls=":",lw=1,color="gray",alpha=0.2)
ax.text(54,0.2,
r"$y=\frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$",{"color":"r","fontsize":20})
ax.set_xlabel("体重")
ax.set_ylabel("概率密度")
ax.set_title(r"体重的直方图: $\mu=60.0$, $\sigma=2.0$",fontsize=16)
plt.show()
3.4 向直方图中添加概率密度曲线和积分区域
# -*- coding:utf-8 -*-import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
mpl.rcParams["font.sans-serif"]=["FangSong"]
mpl.rcParams["axes.unicode_minus"]=False
mu =60.0
sigma =2.0
x = mu+sigma*np.random.randn(500)
bins =50
fig,ax = plt.subplots(1,1)
n,bins,patches = ax.hist(x,
bins,
normed=True,
histtype="bar",
facecolor="cornflowerblue",
edgecolor="white",
alpha=0.75)
y =((1/(np.power(2*np.pi,0.5)*sigma))*
np.exp(-0.5*np.power((bins-mu)/sigma,2)))
ax.plot(bins,y,color="orange",ls="--",lw=2)
integ_x = np.linspace(mu-2*sigma,mu+2*sigma,1000)
integ_y =((1/(np.power(2*np.pi,0.5)*sigma))*
np.exp(-0.5*np.power((integ_x-mu)/sigma,2)))
area =[(mu-2*sigma,0),*zip(integ_x,integ_y),(mu+2*sigma,0)]
poly = Polygon(area,facecolor="gray",edgecolor="k",alpha=0.6,closed=False)
ax.add_patch(poly)
plt.text(0.45,0.2,
r"$\int_{\mu-2\sigma}^{\mu+2\sigma} y\mathrm{d}x$",
fontsize=20,
transform=ax.transAxes)
ax.grid(ls=":",lw=1,color="gray",alpha=0.2)
ax.text(54,0.2,
r"$y=\frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$",{"color":"r","fontsize":20})
ax.set_xlabel("体重")
ax.set_ylabel("概率密度")
ax.set_title(r"体重的直方图: $\mu=60.0$, $\sigma=2.0$",fontsize=16)
plt.show()
3.5 绘图区域嵌套子绘图区域
import matplotlib.pyplot as plt
import numpy as np
mu =75.0
sigma =15.0
bins =20
x = np.linspace(1,100,200)
y = np.random.normal(mu,sigma,200)
fig,ax = plt.subplots()# the main axes
ax.plot(x,y,ls="-",lw=2,color="steelblue")
ax.set_ylim(10,170)# this is an inset axes over the main axes
plt.axes([0.2,0.6,0.2,0.2],fc="k")
count,bins,patches = plt.hist(y,bins,color="cornflowerblue")
plt.ylim(0,28)
plt.xticks([])
plt.yticks([])# this is an inset axes over the inset axes
plt.axes([0.21,0.72,0.05,0.05])
y1 =(1/(sigma * np.sqrt(2* np.pi)))* np.exp(-(bins - mu)**2/(2* sigma**2))
plt.plot(bins,y1,ls="-",color="r")
plt.xticks([])
plt.yticks([])# this is another inset axes over the main axes
plt.axes([0.65,0.6,0.2,0.2],fc="k")
count,bins,patches = plt.hist(y,bins,color="cornflowerblue",normed=True,cumulative=True,histtype="step")
plt.ylim(0,1.0)
plt.xticks([])
plt.yticks([])# this is another inset axes over another inset axes
plt.axes([0.66,0.72,0.05,0.05])
y2 =(1/(sigma * np.sqrt(2* np.pi)))* np.exp(-(bins - mu)**2/(2* sigma**2))
y2 = y2.cumsum()
y2 = y2/y2[-1]
plt.plot(bins,y2,ls="-",color="r")
plt.xticks([])
plt.yticks([])
plt.show()