我有一个二维数组,其中所有数字1到100除以10.每个数字的布尔值是素数还是非素数.我正在努力弄清楚如何像下面的图片一样可视化它.
I have a 2D array of all the numbers 1 to 100 split by 10. And boolean values for each number being prime or not prime. I'm struggling to figure out how to visualize it like in the image below.
这是我的代码,可帮助您了解自己的强项.
Here is my code to help understand what I have better.
我想像这张图片一样在线可视化它.
I want to visualize it like this pic online.
# 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)推荐答案
创建数字的二维数组
查看numpy的文档重塑功能.在这里,您可以通过以下操作将阵列变成2D阵列:
Creating 2D array of the numbers
Check out the documentation for numpy's reshape function. Here you can turn your array into a 2D array by doing:
data = is_prime.reshape(10,10)我们还可以创建前100个整数的数组,以类似的方式用于标记:
we can also make an array of the first 100 integers to use for labeling in a similar fashion:
integers = np.arange(100).reshape(10,10)绘制2D阵列
以2D绘图时,您需要使用matplotlib提供的2D函数之一: imshow,matshow,pcolormesh.您可以直接在数组上调用这些函数,在这种情况下,它们将使用 colormap 和每个像素的颜色将与数组中关联点的值相对应.或者,您可以显式制作RGB图像,从而使您可以更好地控制每个框的颜色.对于这种情况,我认为这样做要容易一些,因此以下解决方案使用该方法.但是,如果您要注释热图,则matplolib文档中有关于此处.现在,我们将创建一个RGB值数组(形状为10 x 10 x 3),并使用numpy的索引功能仅更改素数的颜色.
Plotting the 2D array
When plotting in 2D you need to use one of the 2D functions that matplotlib provides: e.g. imshow, matshow, pcolormesh. You can either call these functions directly on your array, in which case they will use a colormap and each pixel's color will correspond to the value in associated spot in the array. Or you can explicitly make an RGB image which affords you a bit more control over the color of each box. For this case I think that that is a bit easier to do so the below solution uses that approach. However if you want to annotate heatmaps the matplolib documentation has a great resource for that here. For now we will create an array of RGB values (shape of 10 by 10 by 3) and change the colors of only the prime numbers using numpy's indexing abilities.
#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: stackoverflow/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()产生此图像:
更多推荐
使用matplotlib将1D numpy数组可视化为2D数组
发布评论