【问题标题】:Plot matrix of weighted cells in grid with Matplotlib使用 Matplotlib 绘制网格中加权单元的矩阵
【发布时间】:2018-11-25 15:00:38
【问题描述】:

我有一个由随机整数数组构建的方阵,定义如下:

import numpy as np

dim_low, dim_high = 0, 20 #array of random integers' dimensions

matrix = np.random.random_integers(low = dim_low,high = dim_high, size=(dim_high,dim_high))
print(matrix) #the matrix of defined with repetitions of the array.

图中得到的矩阵: https://i.stack.imgur.com/eEcCh.png

如何使用 Matplotlib 绘制在网格中生成的矩阵,以将每个单元格的值(权重)打印在每个单元格的中心,并且在 x 中有一个从 0 到 20 的比例一个 y 轴,如下图 图片 (注意 'x''o' 是示例中的文本,我需要的是权重,整数形式,而不是文本形式):

https://i.stack.imgur.com/9mBuG.png这里

【问题讨论】:

  • 如果您能够生成显示的图像,那么将矩阵元素放在文本中而不是一些字母"o" 有什么区别?您要解决的具体问题是什么?

标签: python matplotlib matrix grid


【解决方案1】:

我从this post 中提取了大部分内容。

import numpy as np
import matplotlib.pyplot as plt

low_dim = 0
high_dim = 20

matrix = np.random.randint(low_dim, high_dim, (high_dim,high_dim))

fig, ax = plt.subplots()

for i in range(0, high_dim):
    for j in range(0, high_dim):
        val = matrix[i,j]
        ax.text(i+0.5, j+0.5, str(val), va='center', ha='center')

ax.set_xlim(low_dim, high_dim)
ax.set_ylim(low_dim, high_dim)
ax.set_xticks(np.arange(high_dim))
ax.set_yticks(np.arange(high_dim))
ax.grid()

plt.show()

【讨论】:

    【解决方案2】:

    适合这个的模块应该是 seaborn。它具有您要求的所有功能以及更多...
    尝试使用https://seaborn.pydata.org/generated/seaborn.heatmap.html。我不会带您了解不同的选项,因为它们的文档非常详细。
    祝你好运!

    顺便说一句,您需要使用 panda 数据透视表以获得舒适的兼容性。

    【讨论】:

      猜你喜欢
      • 2022-12-31
      • 1970-01-01
      • 2015-09-21
      • 2016-09-27
      • 2011-11-08
      • 2018-03-17
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      相关资源
      最近更新 更多