import matplotlib.pyplot as plt
import numpy as np
from math import sin,pi
import pandas as pd
#map() 函数
t = np.arange(0,2.5,0.1)
y1 = list(map(sin,pi*t))
y2 = list(map(sin,pi*t+pi/2))
y3 = list(map(sin,pi*t-pi/2))
plt.plot(t,y1,'b--',t,y2,'g',t,y3,'r-.',linewidth=4.0)
plt.axis([0,3,0,2])
plt.title('my first plot')
plt.show()
#多图划分
t = np.arange(0,2.5,0.05)
y = [x*2 for x in t]
y1 = np.sin(2*pi*t)
y2 = np.cos(2*pi*t)
y3 = np.tan(2*pi*t)
plt.subplot(131)
#text()文本框说明,前两个参数为坐标位置,第三个为文本,数学表达式可以用 LaTex 方式表示,形如:r'$表达式$'
plt.text(0.051,0.051,r'$y = sin(x)$',fontsize=20,bbox={'facecolor':'red','alpha':0.3})#alpha 表透明度
plt.plot(t,y,'ro',t,y1,'b-.',t,y2,'y.-')
plt.grid(True)
plt.legend(['第一系列','第二系列','第三系列'],loc=0)#显示图例,loc 表示位置
plt.xlabel(u'a')
plt.ylabel('b',color='blue')
plt.title('正弦',fontsize=20,fontname='SimHei',color='red')#SimHei 黑体
plt.subplot(132)#将画布划分,竖直一,水平三,第二区域
plt.plot(t,y2,'r--')
plt.subplot(133)
plt.plot(t,y3,'y-')
plt.show()
#处理日期值刻度
import datetime
import matplotlib.dates as mdates
moths = mdates.MonthLocator()
days = mdates.DayLocator()
timeFmt = mdates.DateFormatter('%Y-%m')#刻度日期格式
events = [datetime.date(2015,1,23),datetime.date(2015,1,28),datetime.date(2015,2,2),
datetime.date(2015,2,21),datetime.date(2015,3,12),datetime.date(2015,3,21)]
readings = [11,33,2,-1,21,0]
fig,ax = plt.subplots()
plt.plot(events,readings,)
ax.xaxis.set_major_locator(moths)#设置 x 轴主刻度
ax.xaxis.set_major_formatter(timeFmt)#设置 x 轴刻度格式
ax.xaxis.set_minor_locator(days)#设置 x 轴最小刻度
plt.show()
#设置边框轴线
x = np.arange(-2*pi,2*pi,0.01)
for i in range(1,4):
y = np.sin(i*x)/x
plt.plot(x,y)
plt.xticks([-2*pi,-pi,0,pi,2*pi],[r'$-2\pi$',r'$-\pi$',r'$0$',r'$\pi$',r'$2\pi$'])#设置刻度长度和格式
plt.yticks(range(-1,4))
ax = plt.gca()#获取图边框对象,共4条
ax.spines['right'].set_color('none')#隐藏
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')#设置刻度位置
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
#annotate() 注释函数,(文本,注释点坐标,注释点说明,文本坐标,文本说明,箭头样式(字典形式))
plt.annotate(r'$\lim_{x\to 0}\frac{\sin(x)}{x}=1$',xy=[0,1],
xycoords='data',xytext=[20,30],fontsize=16,textcoords='offset points',
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
plt.show()
#pandas 绘制线性图
data = {'数据一':[1,3,4,3,5],
'数据二':[2,4,5,2,4],
'数据三':[3,2,3,2,1]}
df = pd.DataFrame(data)
print(df['数据一'])
x = ['第一','第二','第三','第四','第五']
plt.plot(x,df,'o')
plt.yticks(range(-3,6))
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
plt.legend(data,loc=2)
plt.show()
#直方图
pop = np.random.randint(0,100,100)
n,bins,patches=plt.hist(pop,bins=20,color='y')
print(n,bins,patches)
#n为落在每个区域的个数,bins为划分区域数(面元)
plt.show()
#条状图
index = np.arange(5)
values1 = [5,7,3,4,5]
values2 = [4,3,5,6,7]
std1 = [0.8,1.0,0.9,1.3,0.5]
bw = 0.3#条状宽度
plt.axis([-0.5,5,0,8])
(x,y,宽度,标准差列表,标准差线样式,标签)
plt.bar(index,values1,bw,yerr=std1,error_kw={'ecolor':'0.1','capsize':5},label='first')
plt.bar(index+bw,values2,bw,yerr=std1,error_kw={'ecolor':'0.4','capsize':5},label='first')
plt.xticks(index+0.5*bw,['A','B','C','D','E'])
plt.axis([0,8,-1,5])
plt.barh(index,values1,bw,xerr=std1,error_kw={'ecolor':'0.1','capsize':5},label='first')
plt.barh(index+bw,values2,bw,xerr=std1,error_kw={'ecolor':'0.4','capsize':5},label='first')
plt.yticks(index+0.5*bw,['A','B','C','D','E'])
plt.xticks([])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['right'].set_color('none')
plt.legend(loc=4)
plt.show()
#pandas数据绘制条状图
data = {'数据一':[1,3,4,3,5],
'数据二':[2,4,5,2,4],
'数据三':[3,2,3,2,1]}
x = range(1,6)
df = pd.DataFrame(data)
plt.plot(x,df)
df.plot(kind='bar')
plt.show()
#条状堆积图
data = {'数据一':[1,3,4,3,5],
'数据二':[2,4,5,2,4],
'数据三':[3,2,3,2,1]}
data = pd.DataFrame(data)
data.plot(kind='barh',stacked=True)
s1 = np.array([1,3,4,3,5])
s2 = np.array([2,4,5,2,4])
s3 = np.array([3,2,3,2,1])
x = range(1,6)
plt.axis([0,6,0,15])
plt.bar(x,data['数据一'],color='r')
plt.bar(x,data['数据二'],color='g',bottom=data['数据一'])#bottom参数指明底层数据
plt.bar(x,data['数据三'],color='b',bottom=(data['数据一']+data['数据二']))
plt.axis([0,15,0,6])
plt.barh(x,data['数据一'],color='r',hatch='xx')
plt.barh(x,data['数据二'],color='g',left=data['数据一'],hatch='\\')
plt.barh(x,data['数据三'],color='b',left=(data['数据一']+data['数据二']),hatch='////')
plt.show()
#对比条状图
x0 = np.arange(8)
y1 = np.array([1,3,4,6,7,2,4,3])
y2 = np.array([3,2,4,5,6,4,3,6])
plt.ylim(-8,8)
plt.bar(x0,y1,0.9,facecolor='r',edgecolor='w')
plt.bar(x0,-y2,0.9,facecolor='b',edgecolor='w')
plt.xticks([])
#为每个数据添加文本的方式
for x,y in zip(x0,y1):
plt.text(x,y+0.05,'%d'%y,ha='center',va='bottom')
for x,y in zip(x0,y2):
plt.text(x,-y-0.05,'%d'%y,ha='center',va='top')
ax = plt.gca()
ax.spines['bottom'].set_position(('data',0))
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.show()
#饼图
data = {'数据一':[1,3,4,3,5],
'数据二':[2,4,5,2,4],
'数据三':[3,2,3,2,1]}
df = pd.DataFrame(data)
df['数据一'].plot(kind='pie',figsize=(3,3))
plt.axis('equal')
labels = ['Nokia','Samsung','Apple','Xiaomi']
values = [10,30,45,15]
color =['yellow','green','red','blue']
explode = [0.2,0,0,0]#表示每份数据的切分程度,0~1,越大,分割程度越高
#autopct参数表示所占比例数据样式,此处表示一位小数
plt.pie(values,labels=labels,colors=color,explode=explode,startangle=180,autopct='%1.1f%%')
plt.axis('equal')
plt.show()
#等值线图
dx,dy = 0.01,0.01
x = np.arange(-2.0,2.0,dx)
y = np.arange(-2.0,2.0,dy)
X,Y = np.meshgrid(x,y)#根据给定的两个参数,生成一一对应的网格坐标矩阵
def f(x,y):
return (1-y**5+x**5)*np.exp(-x**2-y**2)
C = plt.contour(X,Y,f(X, Y),8,colors='black')#根据前三个参数画出等高线,8为线条数量
plt.contourf(X,Y,f(X,Y),5,camp=plt.cm.hot)#f为filled,颜色填充,8将三色分层
plt.clabel(C,inline=1,fontsize=10)#等高线上标明高度(Z值)
plt.colorbar()
plt.show()
# 画圆
t = np.arange(-2*pi,2*pi,0.1)
x = np.cos(t)
y = np.sin(t)
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
plt.plot(x,y,'b-')
plt.axis('equal')
plt.show()
#极区图
N = 8
theta = np.arange(0.,2*np.pi,2*np.pi/N)#极坐标均分
radii = np.array([4,3,4,5,6,8,9,11])
plt.axes([0.025,0.1,0.95,0.8],polar=True)#polar指明极区图
colors = np.array(['#4bb2c5','#c5b47f','#FF83FA','#FFE7BA','#FF69B4','#CDAA7D','#B0C4DE','#97FFFF'])
bars = plt.bar(theta,radii,width=(2*np.pi/N),bottom=0.0,color=colors)#bottom参数为离极点距离
plt.xticks(theta,['a','s','d','f','g','h','j','k'])
plt.yticks(range(0,13,2),[])
for x,y in zip(theta,radii):
plt.text(x,y+0.5,'%s'%y)
plt.show()
#3D曲面
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-2,2,0.1)
Y = np.arange(-2,2,0.1)
X,Y = np.meshgrid(X,Y)
def f(x,y):
return (1-y**5+x**5)*np.exp(-x**2-y**2)
ax.plot_surface(X,Y,f(X,Y),rstride=1,cstride=1,cmap=plt.cm.hot)
ax.view_init(elev=30,azim=125)
plt.show()
#3D条状图
x = np.arange(8)
y = np.random.randint(0,10,8)
y2 = y + np.random.randint(0,3,8)
y3 = y2 + np.random.randint(0,3,8)
y4 = y3 + np.random.randint(0,3,8)
y5 = y4 + np.random.randint(0,3,8)
color = ['#4bb2c5','#c5b47f','#FF83FA','#FFE7BA','#FF69B4','#CDAA7D','#B0C4DE','#97FFFF']
fig = plt.figure()
ax = Axes3D(fig)
ax.bar(x,y,0,zdir='y',color=color)#zdir 指定 y 轴为 z 轴维度
ax.bar(x,y2,5,zdir='y',color=color)
ax.bar(x,y3,10,zdir='y',color=color)
ax.bar(x,y4,15,zdir='y',color=color)
ax.bar(x,y5,20,zdir='y',color=color)
plt.show()
#图中图
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
inner_ax = fig.add_axes([0.6,0.6,0.25,0.25])
x1 = np.arange(10)
y1 = np.random.randint(0,10,10)
y2 = np.random.randint(0,10,10)
ax.plot(x1,y1)
inner_ax.plot(x1,y2)
plt.show()
#子图网格
gs = plt.GridSpec(3,3)#将画布分割成 9 个区域,横三竖三,按列表形式存储位置
fig = plt.figure(figsize=(9,6))
x = np.arange(4)
y1 = [0.3,0.27,0.65,0.48]
y2 = [0.1,0.5,0.2,0.8]
s1 = fig.add_subplot(gs[0,:2])#按列表的形式获取位置,第二行,前两列
s1.plot(x,y1,'r-')
s2 = fig.add_subplot(gs[1,:2])
s2.bar(x,y1,0.1)
s3 = fig.add_subplot(gs[2,0])
s3.barh(y1,x,0.03)
s4 = fig.add_subplot(gs[:2,2])
s4.plot(x,y1,'r*',x,y2,'y^')
s5 = fig.add_subplot(gs[2,1:])
s5.plot(x,y1,'r-',x,y2,'y-^')
plt.show()