Matplotlib - 노트

9759 단어 데이터 분석
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()

좋은 웹페이지 즐겨찾기