Python 中的 2D 网格数据可视化

发布于 2024-12-02 01:45:18 字数 323 浏览 2 评论 0原文

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

I need to visualize some data. It's basic 2D grid, where each cell have float value. I know how to e.g. assign color to value and paint grid in OpenCV. But the point here is that there are so many values so it's nearly impossible to do that. I am looking for some method, where I could use gradient. For example value -5.0 will be represented by blue, 0 - black, and +5.0 as red. Is there any way to do that in Python?

Here is sample data I am talking about

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

箜明 2024-12-09 01:45:18

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

这就是它看起来像:

在此处输入图像描述

颜色条设置的详细信息取自 matplotlib 示例: colorbar_only.py. 它解释了需要的边界数量比颜色数大一。

编辑

您应该注意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")

这会产生:
在此处输入图像描述

编辑 3

添加网格,如下所示 示例,使用grid方法。将网格颜色设置为“白色”与颜色图使用的颜色配合良好(即默认的黑色显示效果不佳)。

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

savefig 调用之前包含此内容会生成此图(为了清楚起见,使用 11x11 网格制作):
在此处输入图像描述
grid 有很多选项,在 matplotlib 文档。您可能感兴趣的一个是linewidth

Matplotlib has the imshow method for plotting arrays:

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

This is what it looks like:

enter image description here

The details for the color bar setup were taken from a matplotlib example: colorbar_only.py. It explains that the number of boundaries need to be one larger then then number of colors.

EDIT

You should note, that imshow accepts the origin keyword, which sets the where the first point is assigned. The default is 'upper left', which is why in my posted plot the y axis has 0 in the upper left and 99 (not shown) in the lower left. The alternative is to set origin="lower", so that first point is plotted in the lower left corner.

EDIT 2

If you want a gradient and not a discrete color map, make a color map by linearly interpolating through a series of colors:

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

This produces:
enter image description here

EDIT 3

To add a grid, as shown in this example, use the grid method. Setting the grid color to 'white' works well with the colors used by the colormap (ie the default black does not show up well).

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

Including this before the savefig call produces this plot (made using 11x11 grid for clarity):
enter image description here
There are many options for grid, which are described in the matplotlib documentation. One you might be interested in is linewidth.

臻嫒无言 2024-12-09 01:45:18

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

这显示:

在此处输入图像描述

How about using 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()

This shows:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文