在Python中将矩阵绘制为一个表

时间:2015-12-14 22:11:09

标签: matplotlib ipython-notebook

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

我想到matplotlib但不知道怎么做。我希望在同一个脚本中完成它,所以不需要在这里和那里粘贴它!

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

当前输出为:

enter image description here

更新

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

输出为bleow:

enter image description here

1 个答案:

答案 0 :(得分:3)

使用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([])

enter image description here