python - 大型 matplotlib 像素图最佳方法

标签 python colors matplotlib figure

我有一个大型 2D 数据集,我想在其中为每个 X、Y 对关联一种颜色,并使用 matplotlib 绘制它。我说的是 1000000 点。我想知道在性能(速度)方面最好的方法是什么,如果你能举出一些例子

最佳答案

如果您处理的是常规网格,只需将其视为图像即可:

import numpy as np
import matplotlib.pyplot as plt

nrows, ncols = 1000, 1000
z = 500 * np.random.random(nrows * ncols).reshape((nrows, ncols))

plt.imshow(z, interpolation='nearest')
plt.colorbar()
plt.show()

enter image description here

如果您随机排列组成规则网格的 x,y,z 三元组,则需要将它们网格化。

本质上,你可能有这样的东西:

import numpy as np 
import matplotlib.pyplot as plt

# Generate some data
nrows, ncols = 1000, 1000
xmin, xmax = -32.4, 42.0
ymin, ymax = 78.9, 101.3

dx = (xmax - xmin) / (ncols - 1)
dy = (ymax - ymin) / (ncols - 1)

x = np.linspace(xmin, xmax, ncols)
y = np.linspace(ymin, ymax, nrows)
x, y = np.meshgrid(x, y)

z = np.hypot(x - x.mean(), y - y.mean())
x, y, z = [item.flatten() for item in (x,y,z)]

# Scramble the order of the points so that we can't just simply reshape z
indicies = np.arange(x.size)
np.random.shuffle(indicies)
x, y, z = [item[indicies] for item in (x, y, z)]

# Up until now we've just been generating data...
# Now, x, y, and z probably represent something like you have.

# We need to make a regular grid out of our shuffled x, y, z indicies.
# To do this, we have to know the cellsize (dx & dy) that the grid is on and
# the number of rows and columns in the grid. 

# First we convert our x and y positions to indicies...
idx = np.round((x - x.min()) / dx).astype(np.int)
idy = np.round((y - y.min()) / dy).astype(np.int)

# Then we make an empty 2D grid...
grid = np.zeros((nrows, ncols), dtype=np.float)

# Then we fill the grid with our values:
grid[idy, idx] = z

# And now we plot it:
plt.imshow(grid, interpolation='nearest', 
        extent=(x.min(), x.max(), y.max(), y.min()))
plt.colorbar()
plt.show()

enter image description here

关于python - 大型 matplotlib 像素图最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6318170/

相关文章:

python - 尝试下载 opencv3 时如何修复 Python 版本错误?

python - 为 PySide 和 web2py 编写

python - 为什么不应该将版本号固定在 Pipfile 中?

python - matplotlib 2.0.0 的默认样式名称是什么?

python - 如何制作与现有固定方面子图宽度相等的附加子图?

Python - Pillow ImageShow.show() 不显示图像(Raspbian)

javascript - Canvas 中随时间变化的颜色(js)/setInterval 的问题

javascript - HighCharts:如何将自定义颜色与渐变相结合

css - 使用不透明度值在 sass 中创建调色板或将不透明颜色转换为基色的最佳方法

python - Matplotlib 直方图在第二个直方图箱中添加了一个小条