Python中的二维网格数据可视化

29 投票
2 回答
69322 浏览
提问于 2025-04-17 00:31

我需要把一些数据可视化。这是一个基本的二维网格,每个格子里都有一个浮点数值。我知道怎么在OpenCV里给这些数值分配颜色并绘制网格。但是问题是,数值太多了,几乎不可能一一处理。我想找一种方法,可以使用渐变色。比如说,值-5.0用蓝色表示,0用黑色表示,+5.0用红色表示。有没有办法在Python中做到这一点?

这里是我说的示例数据

        A       B       C        D
A    -1.045    2.0     3.5    -4.890
B    -5.678    3.2     2.89    5.78

2 个回答

9

你觉得用matplotlib怎么样?

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = Axes3D(fig)

Z = np.array([[-1.045, 2.0, 3.5, -4.890],
              [-5.678, 3.2, 2.89, 5.78]])

X = np.zeros_like(Z)
X[1,:] = 1
Y = np.zeros_like(Z)
Y[:,1] = 1
Y[:,2] = 2
Y[:,3] = 3

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,
        linewidth=0, antialiased=False)
ax.set_zlim3d(-10.0, 10.0)

ax.w_zaxis.set_major_locator(LinearLocator(10))
ax.w_zaxis.set_major_formatter(FormatStrFormatter('%.03f'))

m = cm.ScalarMappable(cmap=cm.jet)
m.set_array(Z)
fig.colorbar(m)

plt.show()

这样会显示:

在这里输入图片描述

57

Matplotlib 有一个叫 imshow 的方法,可以用来绘制数组:

import matplotlib as mpl
from matplotlib import pyplot
import numpy as np

# make values from -5 to 5, for this example
zvals = np.random.rand(100,100)*10-5

# make a color map of fixed colors
cmap = mpl.colors.ListedColormap(['blue','black','red'])
bounds=[-6,-2,2,6]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# tell imshow about color map so that only set colors are used
img = pyplot.imshow(zvals,interpolation='nearest',
                    cmap = cmap,norm=norm)

# make a color bar
pyplot.colorbar(img,cmap=cmap,
                norm=norm,boundaries=bounds,ticks=[-5,0,5])

pyplot.show()

这就是它的效果:

enter image description here

关于颜色条的设置细节是参考了一个 matplotlib 的例子:colorbar_only.py. 这个例子说明了 boundaries 的数量需要比颜色的数量多一个。

编辑

你应该注意,code>imshow 接受一个叫 origin 的参数,这个参数决定了第一个点的位置。默认是'左上角',所以在我发布的图中,y轴的0在左上角,99(未显示)在左下角。你也可以把 origin 设置为"lower",这样第一个点就会绘制在左下角。

编辑 2

如果你想要渐变色而不是离散的颜色图,可以通过线性插值来创建一个颜色图:

fig = pyplot.figure(2)

cmap2 = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
                                           ['blue','black','red'],
                                           256)

img2 = pyplot.imshow(zvals,interpolation='nearest',
                    cmap = cmap2,
                    origin='lower')

pyplot.colorbar(img2,cmap=cmap2)

fig.savefig("image2.png")

这样会产生:

enter image description here

编辑 3

要添加网格,可以参考这个例子,使用 grid 方法。把网格颜色设置为'白色'与颜色图的颜色搭配得很好(比如默认的黑色效果不好)。

pyplot.grid(True,color='white')

savefig 调用之前加上这个,会生成这个图(为了清晰起见,使用了11x11的网格):

enter image description here

关于 grid 有很多选项,可以在 matplotlib 的文档中找到。其中一个你可能会感兴趣的是 linewidth

撰写回答