【问题标题】:Visualize 1D numpy array as 2D array with matplotlib使用 matplotlib 将 1D numpy 数组可视化为 2D 数组
【发布时间】:2019-10-11 08:09:06
【问题描述】:

我有一个 1 到 100 的所有数字除以 10 的二维数组。每个数字的布尔值是素数还是非素数。我正在努力弄清楚如何将其可视化,如下图所示。

这是我的代码,可帮助您了解我的优势。

我想在网上把它想象成这张照片。

# excersize
is_prime = np.ones(100, dtype=bool)  # array will be filled with Trues since 1 = True

# For each integer j starting from 2, cross out its higher multiples:
N_max = int(np.sqrt(len(is_prime) - 1))
for j in range(2, N_max + 1):
    is_prime[2*j::j] = False

# split an array up into multiple sub arrays
split_primes = np.split(is_prime, 10);

# create overlay for numbers
num_overlay = np.arange(100)
split_overlay = np.split(num_overlay, 10)
plt.plot(split_overlay)

【问题讨论】:

  • @ImportanceOfBeingErnest 感谢您为我找到这个。我是全新的,目前正在关注 scipy.org 上的 scipy 讲座笔记。有很多东西要吸收,但这看起来正是我想要的。
  • @ImportanceOfBeingErnest 我很好奇你是否能帮助我了解如何创建一个包含所有数字 1 - 100 的二维数组,而不是先创建一个 1d 数组然后使用 np.split() 将其分成 10 个块?
  • np.arange(1, 101).reshape(10, 10) 会给出一个 10 行中编号为 1 到 100 的二维数组。

标签: numpy matplotlib


【解决方案1】:

创建数字的二维数组

查看 numpy 的 reshape 函数的文档。在这里,您可以通过以下方式将数组转换为二维数组:

data = is_prime.reshape(10,10)

我们还可以创建一个包含前 100 个整数的数组,以类似的方式用于标记:

integers = np.arange(100).reshape(10,10)

绘制二维数组

在 2D 中绘图时,您需要使用 matplotlib 提供的 2D 函数之一:例如imshow,matshow,pcolormesh。您可以直接在数组上调用这些函数,在这种情况下,它们将使用colormap,并且每个像素的颜色将对应于数组中相关点的值。或者你可以明确地制作一个 RGB 图像,让你对每个盒子的颜色有更多的控制。对于这种情况,我认为这样做更容易一些,因此下面的解决方案使用了这种方法。但是,如果您想注释热图,matplolib 文档有一个很好的资源here。现在我们将创建一个 RGB 值数组(形状为 10 x 10 x 3),并使用 numpy 的索引功能仅更改素数的颜色。

#create RGB array that we will fill in
rgb = np.ones((10,10,3)) #start with an array of white
rgb[data]=[1,1,0] # color the places where the data is prime to be white

plt.figure(figsize=(10,10))
plt.imshow(rgb)

# add number annotations
integers = np.arange(100).reshape(10,10)

#add annotations based on: https://stackoverflow.com/questions/20998083/show-the-values-in-the-grid-using-matplotlib
for (i, j), z in np.ndenumerate(integers):
    plt.text(j, i, '{:d}'.format(z), ha='center', va='center',color='k',fontsize=15)

# remove axis and tick labels
plt.axis('off')
plt.show()

生成此图像:

【讨论】:

  • 不错!只是想补充一点,如果边缘对 OP 很重要,他们可以使用plt.pcolormesh,例如喜欢plt.pcolormesh(rgb, edgecolor='black', lw=1); plt.axes().set_aspect('equal')。 (根据pcolormesh,您无法免费获得相同的纵横比。)
猜你喜欢
  • 1970-01-01
  • 2017-06-18
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
相关资源
最近更新 更多