1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# -*- coding: utf-8 -*-
# @Author: “williamlfang”
# @Date: 2021-03-19 15:18:19
# @Last Modified by: “williamlfang”
# @Last Modified time: 2021-03-19 16:18:32
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import six
from matplotlib.ticker import FormatStrFormatter
def render_mpl_table(data, savepath, title = "", col_width=2.0, row_height=0.625, font_size=12,
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
bbox=[0, 0, 1, 1], header_columns=0,
ax=None, **kwargs):
if ax is None:
size = (np.array([0,1]) + np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
fig, ax = plt.subplots(figsize=size)
ax.set_title(title, fontdict={'fontsize': 15, 'fontweight': 'bold', 'color': header_color, 'horizontalalignment':'center'})
ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
# fig.tight_layout()
ax.axis('off')
mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)
mpl_table.auto_set_font_size(False)
mpl_table.set_fontsize(font_size)
for k, cell in six.iteritems(mpl_table._cells):
cell.set_edgecolor(edge_color)
if k[0] == 0 or k[1] < header_columns:
cell.set_text_props(weight='bold', color='w')
cell.set_facecolor(header_color)
else:
cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
# return ax
plt.savefig(savepath)
plt.close()
if __name__ == "__main__":
df = pd.DataFrame()
df['date'] = ['2016-04-01', '2016-04-02', '2016-04-03']
df['calories'] = [2200.343332424, 2100.34, 1500]
df['sleep hours'] = [2200, 2100, 1500]
df['gym'] = [True, False, False]
# ==========================================================================
render_mpl_table(df, savepath= '/tmp/dfm.png', title = "My Title", header_columns=0, col_width=2.0)
# ==========================================================================
|