Export pandas Styled table to image file

user1243477 picture user1243477 · Aug 13, 2017 · Viewed 18.3k times · Source

The code below when run in jupyter notebook renders a table with a colour gradient format that I would like to export to an image file.

The resulting 'styled_table' object that notebook renders is a pandas.io.formats.style.Styler type.

I have not been able to find a way to export the Styler to an image.

I hope someone can share a working example of an export, or give me some pointers.

import pandas as pd
import seaborn as sns

data = {('count', 's25'): 
       {('2017-08-11', 'Friday'): 88.0,
        ('2017-08-12', 'Saturday'): 90.0,
        ('2017-08-13', 'Sunday'): 93.0},
        ('count', 's67'): 
       {('2017-08-11', 'Friday'): 404.0,
        ('2017-08-12', 'Saturday'): 413.0,
        ('2017-08-13', 'Sunday'): 422.0},
        ('count', 's74'): 
       {('2017-08-11', 'Friday'): 203.0,
        ('2017-08-12', 'Saturday'): 227.0,
        ('2017-08-13', 'Sunday'): 265.0},
        ('count', 's79'): 
       {('2017-08-11', 'Friday'): 53.0,
        ('2017-08-12', 'Saturday'): 53.0,
        ('2017-08-13', 'Sunday'): 53.0}}

table = pd.DataFrame.from_dict(data)
table.sort_index(ascending=False, inplace=True)

cm = sns.light_palette("seagreen", as_cmap=True)
styled_table = table.style.background_gradient(cmap=cm)
styled_table

enter image description here

Answer

Shovalt picture Shovalt · Apr 30, 2018

As mentioned in the comments, you can use the render property to obtain an HTML of the styled table:

html = styled_table.render()

You can then use a package that converts html to an image. For example, IMGKit: Python library of HTML to IMG wrapper. Bear in mind that this solution requires the installation of wkhtmltopdf, a command line tool to render HTML into PDF and various image formats. It is all described in the IMGKit page.

Once you have that, the rest is straightforward:

import imgkit
imgkit.from_string(html, 'styled_table.png')