python - 在 python 中的 imshow 中获取正确的轴标签

标签 python matplotlib imshow

我正在使用以下代码生成一些等高线图,

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()

我从 StackExchange 上的某个地方偷了它。我很难简单地让 x 和 y 轴显示正确的域 [-4,4]。已经发布了许多对我不起作用的解决方案,例如 Change values on matplotlib imshow() graph axiscorrecting the axes using imshow但既不保持图像原样,也不重新标记轴。救命!!!

最佳答案

试试这段代码,你必须像我一样在函数 contourimshow 中设置限制:

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) 仅获取一个参数。

关于python - 在 python 中的 imshow 中获取正确的轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785191/

相关文章:

python - 使用 Python 绘制安全性与交易时间的关系图

python - 如何在 matplotlib 中绘制 datetime.time?

python - 将线图添加到 imshow 并更改轴标记

python - 为什么当我将鼠标悬停在 imshow 上时不显示像素值?

python - 从python中的elasticsearch结果中获取准确的值

python - 在python中查找优先级队列中的值

python - 查找数组中总和为给定值的所有元素对

python - 艰难地学习 Python,练习 35

python - 在 matplotlib 上禁用科学记数法

python - imshow() 子图生成不需要的空白