2017-04-09 30 views
1

我正在測試R中的代碼,然後我想在Python中使用類似的代碼。我有這個潛力:Z = 1/sqrt(Y^2+X^2+2*d*X+d^2)。我嘗試使用pracma包裝這樣有R繪製它:R和Python上的漸變函數

require(pracma) 

range = seq(-15,15,by=1) 
mesh = meshgrid(range,range) 

X = mesh$X 
Y = mesh$Y  
d = 5 

# Now I define the potential: 
Z = 1/sqrt(Y^2+X^2+2*d*X+d^2) 
contour(range,range,t(Z),col="black",xlab="x",ylab="y") 

# Now the gradient: 
grX = gradient(Z,range,range)$X 
grY = gradient(Z,range,range)$Y 

# I wanted the vectors to be normalized so I did this: 
grXN = grX/sqrt(grX^2+grY^2) 
grYN = grY/sqrt(grX^2+grY^2) 

# Finally I draw the vector field: 
quiver(X,Y,grXN,grYN,scale=0.5,col="black") 

當我運行這段代碼我得到這個: Quiver in R 這或多或少是我想要的東西,但它是一個有點難看。

然後我做了這個代碼在Python這樣的:

import numpy as np 
import matplotlib.pyplot as plt 

rng = np.arange(-15,15,1) 
X,Y = np.meshgrid(rng,rng) 
d = 5 

# Now I define the potential: 
Z = 1/np.sqrt(Y**2+X**2+2*d*X+d**2) 

# Now the gradient: 
grX,grY = np.gradient(Z) 

# Since I want the vectors normalized I did this: 
grXN = grX/np.sqrt(grX**2+grY**2) 
grYN = grY/np.sqrt(grX**2+grY**2) 

# In this case I made a different contour: 
contor = plt.contourf(X,Y,Z,50) 
cbar = plt.colorbar(contor) 

# Finally the arrows: 
Q = plt.quiver(X,Y,grXN,grYN,color="w",scale=30) 

當我運行這段代碼我得到這個: Quiver in Python 這是可愛的,但是從R.爲什麼得到的結果完全不同?

+0

你用什麼版本的Python? – vaultah

+0

我在使用2.7.13版本 –

回答

0

您的Python箭頭相對於您的R箭簡單地扭轉90°。原因在於尺寸「X」和「Y」的順序在numpymatplotlib之間的約定差異。出於(有爭議的)直覺性的原因,matplotlib的功能(如其瘋狂的叔叔,Matlab)通常會按順序詢問X,然後Y.同樣,從Matlab的老舊的meshgrid函數中獲得靈感,numpy.meshgrid也採用該慣例,因爲它的indexing參數默認爲'xy'。但我認爲numpy.gradient必須遵循更常用的numpy -esquete假設'ij'索引(和可視化數組時,Y通常是行對行'i'維度,其中numpy數組是維0,所以那麼X通常是列尺寸爲1的列尺寸'j')。因此,你實際上應該說:的

grY,grX = np.gradient(Z) 

代替

grX,grY = np.gradient(Z) 
+0

Jajajaja!瘋狂的叔叔!非常感謝你!!!很高興知道,我真的不認爲這是問題所在......它現在完美無缺! –