将矩阵绘制为 table in python

draw matrix as a table in python

我正在尝试用 python 生成一个数据矩阵,并希望将其绘制为 table。 从IPython中,我找到了一个显示api,它可以将矩阵显示为table。但我还是更喜欢: 1.删​​除行索引col和col索引行。 2.数据网格应该均匀分割。

我正在考虑 matplotlib,但不确定该怎么做 it.I 希望在同一个脚本中完成,因此无需到处粘贴!

%matplotlib inline
import numpy as np
import pandas as pd
from IPython.display import display, HTML
import matplotlib.pyplot as plt
print pd.__version__

row = 6
col = row
matrix = np.zeros((row, col))
for i in range(row):
    for j in range(col):
        if i == 0:
            matrix[i][j] = 1
        else:
            matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
df = pd.DataFrame(matrix)
display(df)

当前输出为:

已更新

根据 Brat 的评论,我更新了我的参考代码:

%matplotlib inline
import numpy as np
import pandas as pd
from IPython.display import display, HTML
import matplotlib.pyplot as plt

row = 7
col = row
matrix = np.zeros((row, col))
matrix = matrix.astype(int)
for i in range(row):
    for j in range(col):
        if i == 0:
            matrix[i][j] = 1
        else:
            matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
df = pd.DataFrame(matrix)
#display(df)

w = 5
h = 5
plt.figure(1, figsize=(w, h))
tb = plt.table(cellText=matrix, loc=(0,0), cellLoc='center')

tc = tb.properties()['child_artists']
for cell in tc: 
    cell.set_height(1.0/row)
    cell.set_width(1.0/col)

ax = plt.gca()
ax.set_xticks([])
ax.set_yticks([])

plt.show()

输出如下:

对于 matplotlib,您可以考虑使用 table,例如:

import numpy as np
import matplotlib.pylab as pl

nx = 4
ny = 5
data = np.random.randint(0,10,size=(ny,nx))

pl.figure()
tb = pl.table(cellText=data, loc=(0,0), cellLoc='center')

tc = tb.properties()['child_artists']
for cell in tc: 
    cell.set_height(1/ny)
    cell.set_width(1/nx)

ax = pl.gca()
ax.set_xticks([])
ax.set_yticks([])