Skip to content

Instantly share code, notes, and snippets.

@mpolatcan
Created February 13, 2020 07:21
Show Gist options
  • Save mpolatcan/bfd159af6a96e2b9031e825291503885 to your computer and use it in GitHub Desktop.
Save mpolatcan/bfd159af6a96e2b9031e825291503885 to your computer and use it in GitHub Desktop.
Code snippet that renders DataFrame as image
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import six
import random
df = pd.DataFrame()
df['date'] = ['2016-04-{}'.format(day) for day in range(1, 51)]
df['calories'] = [random.randint(1500, 2000) for i in range(50)]
df['sleep hours'] = [random.randint(6, 10) for i in range(50)]
def render_dataframe(df,
image_name,
col_width=0.625,
row_height=0.425,
font_size=14,
header_color='#40466e',
row_colors=['#f1f1f2', 'w'],
edge_color='w',
bbox=[0, 0, 1, 1],
header_columns=0,
**kwargs):
plt.figure(figsize=(np.array(df.shape[::-1]) + np.array([0,1])) * np.array([col_width, row_height]))
table = plt.table(cellText=df.values, bbox=bbox, colLabels=df.columns, **kwargs)
table.auto_set_font_size(False)
table.set_fontsize(font_size)
for k, cell in six.iteritems(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)])
plt.axis('off')
plt.tight_layout()
plt.savefig(image_name)
render_dataframe(df, "test.png", header_columns=0, col_width=2.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment