import math, random, pylab
class Location(object): #位置類
def __init__(self, x, y): #給定座標,完成初始化
self.x = float(x)
self.y = float(y)
def move(self, xc, yc):#移動,XY方向各變化
return Location(self.x+float(xc), self.y+float(yc))
def getCoords(self): #響應,返回當前座標
return self.x, self.y
def getDist(self, other): #響應,計算與給定點的距離。
ox, oy = other.getCoords()
xDist = self.x - ox
yDist = self.y - oy
return math.sqrt(xDist**2 + yDist**2)
class CompassPt(object): #方向類
possibles = ('N', 'S', 'E', 'W')
def __init__(self, pt): #PT:方向,只給從NSEW中選擇。
if pt in self.possibles: self.pt = pt
else: raise ValueError('in CompassPt.__init__')
def move(self, dist): #移動方向,N,X方向不變,Y增長DIST
if self.pt == 'N': return (0, dist)
elif self.pt == 'S': return (0, -dist)
elif self.pt == 'E': return (dist, 0)
elif self.pt == 'W': return (-dist, 0)
else: raise ValueError('in CompassPt.move')
class Field(object): #場地類
def __init__(self, drunk, loc): #酒鬼名字和起點座標
self.drunk = drunk
self.loc = loc #給定的位置
def move(self, cp, dist): #cp是個對象,待查
oldLoc = self.loc
xc, yc = cp.move(dist)
self.loc = oldLoc.move(xc, yc)
def getLoc(self):
return self.loc
def getDrunk(self):
return self.drunk
class Drunk(object):
def __init__(self, name):
self.name = name
def move(self, field, time = 1):#好多的move()
if field.getDrunk() != self:
raise ValueError('Drunk.move called with drunk not in field')
for i in range(time):#酒鬼決定方向
pt = CompassPt(random.choice(CompassPt.possibles))
field.move(pt, 1)#酒鬼決定移動
def performTrial(time, f):#測試,輸入次數,場地對象
start = f.getLoc() #超點位置
distances = [0.0] #起點距離
for t in range(1, time + 1):
f.getDrunk().move(f)#從field得到酒鬼對象,再得到他的 move
newLoc = f.getLoc()#移動後得到再位置
distance = newLoc.getDist(start)#計算距離,
distances.append(distance) #將距離追加到列表
return distances
##三次測試結果記錄
drunk = Drunk('Homer Simpson')
for i in range(5):
f = Field(drunk, Location(0, 0))
distances = performTrial(500, f)
pylab.plot(distances)
pylab.title('Homer\'s Random Walk')
pylab.xlabel('Time')
pylab.ylabel('Distance from Origin')
def performSim(time, numTrials):
distLists = []
for trial in range(numTrials):
d = Drunk('Drunk' + str(trial))
f = Field(d, Location(0, 0))
distances = performTrial(time, f)
distLists.append(distances)
return distLists
def ansQuest(maxTime, numTrials):
means = []
distLists = performSim(maxTime, numTrials)
for t in range(maxTime + 1):
tot = 0.0
for distL in distLists:
tot += distL[t]
means.append(tot/len(distLists))
pylab.figure()
pylab.plot(means)
pylab.ylabel('distance')
pylab.xlabel('time')
pylab.title('Average Distance vs. Time (' + str(len(distLists)) + ' trials)')
ansQuest(500, 300)
pylab.show()
順便上兩張生成的模擬圖
###########
class oddField(Field):
def move(self,cp,dist):
Field.move(self,cp,dist)
newLoc = self.loc
x,y = newLoc.getCoords()
if math.fabs(x) == math.fabs(y):
self.loc = Location(0,0)
class usualDrunk(
Drunk):
def move(self,field,dist=1):
cp = random.choice(CompassPt.possibles)
Drunk.move(self,field,CompassPt(cp),dist)
class coldDrunk(
Drunk):
def move(self,field,dist=1):
cp = random.choice(CompassPt.possibles)
if cp == S:
Drunk.move(self,field,CompassPt(cp),2*dist)
else:
Drunk.move(self,field,CompassPt(cp),dist)
class ewDrunk(
Drunk):
def move(self,field,dist=1):
cp = random.choice(CompassPt.possibles)
while cp != E and cp!=W:
cp = random.choice(CompassPt.possibles)
Drunk.move(self,field,CompassPt(cp),dist)
####python 代碼格式化
http://tool.oschina.net/codeformat/jsgit
class Drunk(object);
def __init__(self, name);
self.name = name def move(self, field, cp, dist = 1);
if field.getDrunk().name != self.name;
raise ValueError('Drunk.move called with drunk not in field')
for i in range(dist);
field.move(cp, 1)github
class ColdDrunk(Drunk);
def move(self, field, dist = 1);
cp = random.choice(CompassPt.possibles)
if cp == 'S';
Drunk.move(self, field, CompassPt(cp), 2 * dist)
else;
Drunk.move(self, field, CompassPt(cp), dist)web
class UsualDrunk(Drunk);
def move(self, field, dist = 1);
cp = random.choice(CompassPt.possibles)
Drunk.move(self, field, CompassPt(cp), dist)app
class EWDrunk(Drunk);
def move(self, field, time = 1);
cp = random.choice(CompassPt.possibles)
while cp != 'E'and cp != 'W';
cp = random.choice(CompassPt.possibles)
Drunk.move(self, field, CompassPt(cp), time) def performSim(time, numTrials, drunkType);
distLists = []
for trial in range(numTrials);
d = drunkType('Drunk' + str(trial))…def ansQuest(maxTime, numTrials, drunkType, title);
means = [] distLists = performSim(maxTime, numTrials, drunkType)…ansQuest(500, 100, UsualDrunk, ‘UsualDrunk’)dom
class oddField(Field);
def isChute(self);
x,
y = self.loc.getCoords() return abs(x) - abs(y) == 0 def move(self, cp, dist);
Field.move(self, cp, dist) if self.isChute();
self.loc = Location(0, 0)""函數
###########2
https://www.cnblogs.com/webary/p/5813855.html
一提到python繪圖,matplotlib是不得不提的python最著名的繪圖庫,它裏面包含了相似matlab的一整套繪圖的API。所以,做爲想要學習python繪圖的童鞋們就得在本身的python環境中安裝matplotlib庫了,安裝方式這裏就很少講,方法有不少,給個參考的。post
本文將在已安裝matplotlib的環境中教新手如何快速使用其中的接口進行繪圖操做,並展示一個很是直觀的繪圖例子,以及控制繪圖中的一些細節的方法。學習
既然繪圖要用matplotlib的包,而且咱們也已經安裝了,那麼首先確定是要引入這個包了: import matplotlib.pyplot as plt
固然也能夠替換爲引入pylab(是matplotlib的一個子包,很是適合於進行交互式繪圖,本文將以這個爲例): import pylab as pl
接下來,就是對具體數據進行繪圖了。好比咱們要繪製一條y=x^2的曲線,可這樣寫代碼:
x = range(10) # 橫軸的數據
y = [i*i for i in x] # 縱軸的數據
pl.plot(x, y) # 調用pylab的plot函數繪製曲線
pl.show() # 顯示繪製出的圖
執行以後就能夠看到繪製出來的圖了:
![](http://static.javashuo.com/static/loading.gif)
能夠看到,要顯示一個圖很是簡單,只要有了兩個list做爲輸入數據,前後調用plot和show函數就能夠了。必定要記得只有調用了show以後纔會顯示出來!只有plot是不行的!
在實際運用中,可能這樣一條簡單粗暴的線可能並非咱們想要的最好的結果,好比,想要在圖形上顯示原始數據點,很簡單,只要在plot函數中加上一個參數便可: pl.plot(x, y, 'ob-') # 顯示數據點,並用藍色(blue)實現繪製該圖形
這個參數用法比較靈活,能夠從下面的值中組合選擇:
顏色(color 簡寫爲 c):
藍色: 'b' (blue)
綠色: 'g' (green)
紅色: 'r' (red)
藍綠色(墨綠色): 'c' (cyan)
紅紫色(洋紅): 'm' (magenta)
黃色: 'y' (yellow)
黑色: 'k' (black)
白色: 'w' (white)
線型(linestyle 簡寫爲 ls):
實線: '-'
虛線: '--'
虛點線: '-.'
點線: ':'
點: '.' 點型(標記marker):
像素: ','
圓形: 'o'
上三角: '^'
下三角: 'v'
左三角: '<'
右三角: '>'
方形: 's'
加號: '+'
叉形: 'x'
棱形: 'D'
細棱形: 'd'
三腳架朝下: '1'(像'丫')
三腳架朝上: '2'
三腳架朝左: '3'
三腳架朝右: '4'
六角形: 'h'
旋轉六角形: 'H'
五角形: 'p'
垂直線: '|'
水平線: '_'
線是調好了,但是還想加上橫縱座標的說明呢?也很簡單,在調用show函數以前添加以下代碼:
pl.xlabel(u"我是橫軸")
pl.ylabel(u"我是縱軸")
效果以下:
![](http://static.javashuo.com/static/loading.gif)
這裏必定要記住,傳遞的字符串必定要是Unicode編碼,若是是直接傳入字符串,形式如 u'這裏是要寫的字符串' 便可。
如今就直觀多了吧,終於像一個正常的圖了,不過,還想再在圖裏加個圖例該咋辦?也不難,繼續給plot傳參數:
pl.plot(x, y, 'ob-', label=u'y=x^2曲線圖') # 加上label參數添加圖例
pl.legend() # 讓圖例生效
這裏也是同樣,label字符串參數務必加上u''聲明爲unicode編碼,不然圖例將會添加失敗。效果圖以下:
![](http://static.javashuo.com/static/loading.gif)
oh,看到圖像上面光禿禿的,就好想給它加個標題: pl.title(u'圖像標題') # 字符串也須要是unicode編碼
有時候,咱們的數據可能分佈並無這麼集中,好比咱們想要對項目中的某些數據進行繪圖觀察時發現,大量數據彙集在0附近,而少許很大的數據會致使圖像顯示效果很很差,好比:
x = range(10)+[100]
y = [i*i for i in x]
pl.plot(x, y, 'ob-', label=u'y=x^2曲線圖')
![](http://static.javashuo.com/static/loading.gif)
這時,咱們想要限制須要顯示的座標範圍:
pl.xlim(-1, 11) # 限定橫軸的範圍
pl.ylim(-1, 110) # 限定縱軸的範圍
再上效果圖:
![](http://static.javashuo.com/static/loading.gif)
好了,到這裏plot的經常使用繪圖用法就講完了,另外,若是須要在一幅圖中顯示多條線,能夠在show函數調用前繼續調用plot函數,傳入須要繪製的數據和圖形顯示要求。
matplotlib是個很是好用的庫,不論是對於須要寫論文畫圖,仍是數據調研中看數據相關性,都是一個得力助手。寫這篇文章的背景是我以前在項目中也使用這個作了一個特徵與結果之間的相關性調研中使用到了繪圖,就學習了一下,下面是對真實數據進行屏蔽改寫以後的一個很像的示意圖(感興趣的能夠到我github中看源碼,本文的完整代碼及註釋也可在本連接只中找到):
本文簡要介紹了下python繪圖入門的一些用法,若有不對之處,歡迎你們指正。我也是不久前纔開始真正使用python,這個強大而方便的語言會讓咱們能更快地實現本身的想法,你們有比較好的python資料也歡迎留言,共同窗習,謝謝!
轉載請註明出處:使用matplotlib,pylab進行python繪圖(http://www.cnblogs.com/webary/p/5813855.html)