我会使用LaTeX生成表格,因为它们看起来很漂亮,你可以生成图像或直接将它们放在你的文档中。我用以下代码实现了这个目标:
#!/usr/bin/env
import numpy as np
import os
x = np.array([[1,2],[3,4]])
def generateLatexTable(x):
start = [r'\documentclass[preview]{standalone}', r'\begin{document}', r'\begin{tabular}{%s}' % ('{1}{0}{1}'.format('|'.join(['r'] * x.shape[1]), '|')), r'\hline']
tab = [' & '.join(['%d' % val for val in row]) + r' \\ \hline' for row in x]
end = [r'\end{tabular}', r'\end{document}']
text = '\n'.join(start + tab + end)
return text
with open('table.tex', 'w') as f:
f.write(generateLatexTable(x))
os.system("pdflatex table.tex")
以下是另一个示例,使用一个14 x 14的大矩阵,其中填充了从0到100的随机数:
matplot
的table
函数绘制简单表格。此外,您可以将绘制的图形保存为PNG格式。
以下是满足您需求的简单代码:import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,2],[3,4]])
plt.figure()
plt.table(cellText=x,cellLoc='center',loc='center')
plt.axis('off')
plt.savefig('table.png')
通过在 plt.figure(figsize=(x,y))
行中更改 figsize
参数,可以调整图形或图像的大小。
为了获得更好的外观效果,可以按以下方式进行修改:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,2],[3,4]])
fig = plt.figure(figsize=(2,2))
plt.axis('off')
plt.axis('tight')
plt.table(cellText=x,cellLoc='center',loc='center')
#plt.subplots_adjust(hspace=0.5)
fig.tight_layout()
plt.savefig('table.png')
fig = plt.figure(figsize = x.shape)
。 - Daniel F也许这能帮助你:
from matplotlib import pyplot as plt
import numpy as np
w = 10
h = 10
img = np.random.randint(255, size=(w, h))
plt.figure(figsize=(5,8))
plt.imshow(img, interpolation='nearest')
plt.axis('off')
cellTextimg = []
for j in range(0,h):
cellTextimg.append(img[j,:])
the_table = plt.table(cellText= cellTextimg, loc='bottom')
table
是一个不错的起点。我还没有使用它足够多,无法给出一个好的答案。 - Warren Weckessertable
。 - Warren Weckesser