一、图示
二、代码
from matplotlib import pyplot as plt
import numpy as np
from pandas import *
def plot_table(row, col, vals):
"""
函数功能: 绘制二维表格,草图如下:
-----------------
|col1 |col2 |
-----------------
row1|value|value|
-----------------
row2|value|value|
-----------------
输入:
row:string,(N) #['row1', 'row2']
col:string,(M) #['col1', 'col2']
vals:np, (N,M)
"""
R, C = len(row), len(col)
idx = Index(row)
df = DataFrame(np.random.randn(R, C), index=idx, columns=col)
# 根据行数列数设置表格大小
figC, figR = 2.25*C, R
fig = plt.figure(figsize=(figC, figR))
# 设置fig并去掉边框
ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
the_table=plt.table(cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths = [0.1]*vals.shape[1], rowLoc='center', loc='center',cellLoc='center')
the_table.set_fontsize(20)
# 伸缩表格大小常数
the_table.scale(figR/R*2 ,figC/C*1.5)
三、使用
1、 导入包
from matplotlib import pyplot as plt
import numpy as np
from pandas import *
2、构造参数
S =[
[1,0.44,0.29,0.33],
[0.44,1,0.35,0.32],
[0.29,0.35,1,0.60],
[0.33,0.32,0.60,1]
]
row = ["Chinese","English","Math","Physics"]
col = ["Chinese","English","Math","Physics"]
vals = np.array(S)
3、绘制
plot_table(row, col, vals)