【问题标题】:Large matplotlib pixel figure best approach大型matplotlib像素图最佳方法
【发布时间】:2011-09-13 04:11:15
【问题描述】:

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

【问题讨论】:

  • 点在规则网格上吗?你想让它们在一个普通的网格上吗?您需要提供更多信息!不过,1e6 的分数并不多。如果这是您想要的,您应该可以使用散点图。图像的 1e6 像素根本不算多,所以如果这些点在规则网格上,那你也没有问题......
  • 你看过imshow吗? matplotlib.sourceforge.net/api/… 您究竟想如何指定 X、Y 对的颜色?您想要每 1e6 个位置都有一个独特的颜色吗? (无法在视觉上区分 1e6 种颜色...)您想将该值映射到颜色条吗? (这是imshow 默认所做的)
  • 我想要一个 bmp 图,其中每个 x,y 对都有一个取决于值的颜色,我会看看你的答案

标签: python colors matplotlib figure


【解决方案1】:

如果您正在处理常规网格,只需将其视为图像:

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

如果您有随机排序的 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()

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2021-01-29
    • 2020-11-28
    • 1970-01-01
    • 2018-11-30
    • 2014-02-17
    • 1970-01-01
    • 2022-06-25
    相关资源
    最近更新 更多