[英]How to add axis labels to imshow plots in python?
我從該網站復制(並簡化)以下代碼,以使用imshow
具有兩個變量的函數的結果。
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
# the function that I'm going to plot
def z_func(x,y):
return (x+y**2)
x = arange(-3.0,3.0,0.1)
y = arange(-3.0,3.0,0.1)
X,Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid
im = imshow(Z,cmap=cm.RdBu) # drawing the function
colorbar(im) # adding the colobar on the right
show()
如何將軸標簽(如'x'
和'y'
或'var1
和'var2'
)添加到圖中? 在 RI 中,將在(大部分)繪圖函數中使用xlab = 'x'
。
我試過im.ylabel('y')與
AttributeError: 'AxesImage' 對象沒有屬性 'ylabel'
除此之外,我只找到了如何刪除軸標簽,但沒有找到如何添加它們。
額外問題:如何使刻度范圍從-3
到3
而不是從0
到60
?
要指定軸標簽:
關於您的獎金問題,請考慮extent
kwarg 。 (感謝@Jona)。
此外,請考慮PEP 8 - Python 代碼風格指南推薦的絕對導入:
推薦使用絕對導入,因為如果導入系統配置不正確(例如當包內的目錄最終位於 sys.path 上時),它們通常更具可讀性並且往往表現更好(或至少給出更好的錯誤消息)
import matplotlib.pyplot as plt
import numpy as np
# the function that I'm going to plot
def z_func(x,y):
return (x+y**2)
x = np.arange(-3.0,3.0,0.1)
y = np.arange(-3.0,3.0,0.1)
X,Y = np.meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid
plt.xlabel('x axis')
plt.ylabel('y axis')
im = plt.imshow(Z,cmap=plt.cm.RdBu, extent=[-3, 3, -3, 3]) # drawing the function
plt.colorbar(im) # adding the colobar on the right
plt.show()
你會得到:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.