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

2024-06-07 11:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要可视化一些数据。这是基本的二维网格,每个单元格都有浮点值。我知道如何在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

Tags: 数据方法网格重点颜色可视化绘制opencv
2条回答

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的数目需要比颜色数目大一个。

编辑

您应该note,即imshow接受origin关键字,该关键字设置分配第一个点的位置。默认值是“左上角”,这就是为什么在我发布的绘图中,y轴左上角有0,左下角有99(未显示)。另一种方法是设置origin="lower",以便在左下角绘制第一个点。

编辑2

如果需要渐变而不是离散颜色贴图,请通过linearly interpolating通过一系列颜色生成颜色贴图:

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

要添加网格,如example所示,请使用grid方法。将网格颜色设置为“白色”可以很好地与颜色映射使用的颜色配合使用(即默认的黑色不会很好地显示)。

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

savefig调用生成此绘图之前包含此内容(为清晰起见,使用11x11网格生成): enter image description here matplotlibdocumentation中描述了grid的许多选项。你可能对linewidth感兴趣。

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

这表明:

enter image description here

相关问题 更多 >

    热门问题