【问题标题】:How to add axis labels to imshow plots in python?如何在 python 中的 imshow 图中添加轴标签?
【发布时间】:2019-05-09 14:59:24
【问题描述】:

我从this website 复制(并简化)以下代码,使用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')?在 R 中,我会在(大部分)绘图函数中使用xlab = 'x'

我尝试了im.ylabel('y')

AttributeError: 'AxesImage' 对象没有属性 'ylabel'

除此之外,我只找到how to remove the axis labels,但没有找到如何添加它们。

额外问题:如何让刻度范围从-33 而不是从060

【问题讨论】:

标签: python numpy matplotlib data-visualization axis-labels


【解决方案1】:

指定坐标轴标签:

关于您的额外问题,请考虑extent kwarg。 (感谢@Jona)。

此外,请考虑PEP 8 -- Style Guide for Python Code 推荐的绝对导入:

建议使用绝对导入,因为它们通常更具可读性 并且往往表现得更好(或至少给出更好的错误消息) 如果导入系统配置不正确(例如当一个 包内的目录以 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()

你会得到:

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    相关资源
    最近更新 更多