1. 程式人生 > >matplotlib庫學習(一)

matplotlib庫學習(一)

#matplotlib模組學習
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5,5,50)
y1 = 2*x + 1
y2 = x**2
#畫一個直線
plt.figure()
plt.plot(x,y1)
plt.show()

這裡寫圖片描述

#在同一個fig中畫兩條線
plt.figure(num=3,figsize=(8,6)) #num對應圖的序號,figsize對應圖的大小
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--'
) plt.show()

這裡寫圖片描述

#設定座標軸區間
plt.figure()
plt.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('x axis')
plt.ylabel('y axis')

#修改座標項
new_ticks = np.linspace(-1
,2,5) print new_ticks #修改x軸的範圍 plt.xticks(new_ticks) #設定 plt.yticks(new_ticks,[r'$apple$',r'$banana$',r'$pear$',r'$food\ food$',r'rice']) plt.show()
[-1.   -0.25  0.5   1.25  2.  ]
#修改座標軸的樣子
ax = plt.gca() #獲取當前座標軸
ax.spines['right'].set_color('none') #刪除座標頂部橫線
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom'
) # ACCEPTS: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ] ax.spines['bottom'].set_position(('data', 0)) #設定Y軸的座標原點 # the 1st is in 'outward' | 'axes' | 'data' # axes: percentage of y axis # data: depend on y data ax.yaxis.set_ticks_position('left') # ACCEPTS: [ 'left' | 'right' | 'both' | 'default' | 'none' ] ax.spines['left'].set_position(('data',0)) #設定X軸的座標原點 plt.show()

這裡寫圖片描述

plt.figure()
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
#設定legend
plt.legend(handles=[l1,l2],labels=['line1','line2'],loc='best') 
"""legend( handles=(line1, line2, line3),
           labels=('label1', 'label2', 'label3'),
           'upper right')
    The *loc* location codes are::
          'best' : 0,          (currently not supported for figure legends)
          'upper right'  : 1,
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,"""
plt.show()

這裡寫圖片描述

#添加註解
#先畫出一條直線

x = np.linspace(-3,3,50)
y = x*2 + 1

plt.figure()
plt.plot(x,y)

#修改座標軸
ax = plt.gca()
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))
plt.show()

這裡寫圖片描述

#新增點
x0 = 1
y0 = 2*x0 + 1
#畫一個點
plt.scatter(x0,y0,s = 50,color='b')
#畫一天直線
plt.plot([x0,x0,],[y0,0,],'k--',linewidth=2.5)

這裡寫圖片描述

#annotate 1
plt.annotate(r'$2x+1=%s'%y0,xy=(x0,y0),xycoords='data',xytext=(+30,-30),
            textcoords='offset points',fontsize=16,
            arrowprops=dict(arrowstyle='->',connectionstyle="arc3,rad=.2"))
#annotate 2
plt.text(-3.5, 3, r'$This\ is\ the\ some\ text.$',
         fontdict={'size': 16, 'color': 'r'})

這裡寫圖片描述

#散點圖
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
C = np.arctan2(Y,X) # for color value

plt.scatter(X,Y,s=75,c=C,alpha=0.5)

plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))
#設定x,y軸影藏
plt.xticks(())
plt.yticks(())
plt.show()

這裡寫圖片描述

#柱狀圖
n  = 12
X = np.arange(n)
Y1 = (1-X/float(n))*np.random.uniform(0.5,1,n)
Y2 = (1-X/float(n))*np.random.uniform(0.5,1,n)

plt.bar(X,Y1,facecolor='#9999ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')

for x,y in zip(X,Y1):
    #ha:horizatal alignment
    plt.text(x,y+0.05,'%.2f'%y,ha='center',va='bottom')

for x,y in zip(X,Y2):
    #ha:horizatal alignment
    #va:vertial alignment
    plt.text(x,-y-0.05,'-%.2f'%y,ha='center',va='top')

plt.xlim(-0.5,n)
plt.ylim(-1.25,1.25)
plt.xticks(())
plt.yticks(())

plt.show()

這裡寫圖片描述

#等高線
def f(x,y):
    #計算高度函式
    return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)

n= 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x,y)

#10代表登高線條數-1
plt.contour(X,Y,f(X,Y),10,alpha=0.75,cmap=plt.cm.hot)
#畫線上數字
C = plt.contour(X,Y,f(X,Y),10,color='black',linewidth=.5)
#新增到等高圖上
plt.clabel(C,inline=True,fontsize=10)

plt.xticks(())
plt.yticks(())
plt.show()

這裡寫圖片描述