2016-06-13 516 views
1

我使用下面的代碼生成一些等高線圖,得到正確的座標軸標籤中imshow在python

from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show 
import numpy as np 
from numpy import exp,arange 
import matplotlib.pyplot as plt 

def z_func(x,y): 
    func = 3.0*(1.0 - x)**2*np.exp(-x**2 - (y+1.0)**2) - 10.0*(x/5.0 - x**3 - y**5)*np.exp(-x**2 - y**2) - 0.33*np.exp(-(x + 1.0)**2 - y**2) 
    return func 


x = arange(-4.0,4.0,0.1) 
y = arange(-4.0,4.0,0.1) 
X,Y = meshgrid(x, y) # grid of point 
Z = z_func(X, Y) 

fig = plt.figure(figsize=(10,6)) 
im = imshow(Z,cmap=cm.RdBu) # drawing the function 
# adding the Contour lines with labels 
cset = contour(Z,arange(-1,1.5,0.2),linewidths=2,cmap=cm.Set2) 
clabel(cset,inline=True,fmt='%1.1f',fontsize=10) 
colorbar(im) # adding the colobar on the right 
# latex fashion title 
title('peaks function') 
show() 

我偷了從somehwere上StackExchange。我很難得到x和y軸來顯示正確的域,[-4,4]。已經發布了許多不適合我的解決方案,例如Change values on matplotlib imshow() graph axiscorrecting the axes using imshow,但它們都沒有保持圖像的方式並重新映射軸。幫幫我!!!

+0

此代碼無法使用。你只是想爲imshow設置軸限制嗎? – Serenity

+0

該代碼適用於我。我忘了我的進口...讓我現在進入。我想要軸反映我的輸入變量的實際範圍,[-4,4] – superhero

回答

1

試試這個代碼,你有兩種功能contour設置限制和imshow像我一樣:

import matplotlib.pylab as plt 
import numpy as np 

x = np.arange(-4.0,4.0,0.1) 
y = np.arange(-4.0,4.0,0.1) 
X,Y = np.meshgrid(x, y) # grid of point 
Z = X**2. * np.sin(Y) 

fig = plt.figure(figsize=(10,6)) 
im = plt.imshow(Z,cmap=plt.cm.RdBu, extent=(-4,4,-4,4)) # drawing the function 
# adding the Contour lines with labels 
cset = plt.contour(Z,np.arange(-1,1.5,0.2),linewidths=2,cmap=plt.cm.Set2, extent=(-4,4,-4,4)) 
plt.clabel(cset,inline=True,fmt='%1.1f',fontsize=10) 
plt.colorbar(im) # adding the colobar on the right 
# latex fashion title 
plt.title('peaks function') 
plt.show() 

enter image description here

。在你的代碼中的問題:Z已經是一個二維數組但z_fun_optimization(x)只能獲得一個參數。

+0

剪切和粘貼錯誤。我的錯:-0。更新的代碼就在那裏。這雖然做到了!我忘記在輪廓參數中加入'extent'參數。謝謝! – superhero