gpt4 book ai didi

Python:带有 imshow 的 2D 彩色 map

转载 作者:行者123 更新时间:2023-12-05 09:22:44 25 4
gpt4 key购买 nike

我正在尝试使用颜色在二维图形上表示两个变量的函数。我遇到了这个例子 here :

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 (1-(x**2+y**3))*exp(-(x**2+y**2)/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
# 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('$z=(1-x^2+y^3) e^{-(x^2+y^2)/2}$')
show()

产生 enter image description here

但是,轴的比例和范围与真实的 x 和 y 数据(均在 -3 和 3 之间)不对应。如何使它们与实际数据对应?

最佳答案

我不会使用 imshow 绘制二维函数,imshow 用于显示图像。

坐标轴标签来自“像素”的数量。你的值(value)观。

要绘制二维函数,请使用 plt.pcolormesh

这需要一个像素网格,您应该在该网格的中心评估您的函数。这将导致清晰的像素:

import numpy as np
import matplotlib.pyplot as plt


def z_func(x, y):
return (1 - (x ** 2 + y ** 3)) * np.exp(-(x ** 2 + y ** 2) / 2)

x = np.arange(-3.0, 3.0, 0.1)
y = np.arange(-3.0, 3.0, 0.1)
x_center = 0.5 * (x[:-1] + x[1:])
y_center = 0.5 * (y[:-1] + y[1:])

X, Y = np.meshgrid(x_center, y_center)
Z = z_func(X, Y)

# pcolormesh needs the pixel edges for x and y
# and with default flat shading, Z needs to be evaluated at the pixel center
plot = plt.pcolormesh(x, y, Z, cmap='RdBu', shading='flat')

# contour needs the centers
cset = plt.contour(X, Y, Z, cmap='gray')
plt.clabel(cset, inline=True)

plt.colorbar(plot)
plt.savefig('plot_z_flat.png')


flat shading

您也可以使用 gouraud 着色来获得平滑的图像,但是您必须像这样评估边缘上的函数:


import numpy as np
import matplotlib.pyplot as plt


def z_func(x, y):
return (1 - (x ** 2 + y ** 3)) * np.exp(-(x ** 2 + y ** 2) / 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)
Z = z_func(X, Y)

# pcolormesh needs the pixel vertices for x and y
# and with gouroud shading, Z has to be evaluated on all vertices
plot = plt.pcolormesh(X, Y, Z, cmap='RdBu', shading='gouraud')

# countour needs the center points
x_center = 0.5 * (x[:-1] + x[1:])
y_center = 0.5 * (y[:-1] + y[1:])
X, Y = np.meshgrid(x, y)
Z = z_func(X, Y)

cset = plt.contour(X, Y, Z, cmap='gray')
plt.clabel(cset, inline=True)

plt.colorbar(plot)
plt.show()

gouraud shading

关于Python:带有 imshow 的 2D 彩色 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24897681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com