Pandas DataFrame plotting with Highcharts

pandas_highcharts is a Python library to turn your pandas DataFrame into a suited JSON for Highcharts, a Javascript library for interactive charts.

Before introducing Highcharts, I build an arbitrary DataFrame with a timeseries (a Brownian motion), plot it with matplotlib, then seaborn and Highcharts.

Import


In [7]:
%matplotlib notebook
import string

import numpy as np
import pandas as pd

from pandas_highcharts.core import serialize
from IPython.core.display import display, HTML
from pandas_highcharts.core import json_encode
from collections import defaultdict
from datetime import datetime as dt

In [23]:
data = defaultdict(lambda: defaultdict(dict))

data['chart']['type'] = 'columnrange'
data['chart']['inverted'] = True
data['chart']['zoomType'] = 'y'
data['chart']['panning'] = True
data['chart']['panKey'] = 'shift'
data['chart']['renderTo'] = 'bepitimeline'

# data['title'] = {}
data['title']['text'] = 'BepiTimeline Test'

# data['scrollbar'] = {}
data['scrollbar']['enable'] = True

# data['xAxis'] = {}
data['xAxis']['categories'] = ['MERTIS', 'BELA', 'MGNS', 'PHEBUS']

# data['yAxis'] = {}
data['yAxis']['type'] = 'datetime'

# data['yAxis']['title'] = {}
data['yAxis']['title']['text'] = 'Timespan'

# data['plotOptions'] = {}
# data['plotOptions']['columnrange'] ={}
data['plotOptions']['columnrange']['grouping'] =  False

# data['legend'] = {}
data['legend']['enabled'] = True

data['tooltip']['headerFormat'] = '<b>{series.name}</b><br/>'
data['tooltip']['pointFormat'] = 'Mode: {point.mode}. <br> {point.low} - {point.high}'
data['tooltip']['formatter'] = ''

data['series'] = []

In [24]:
timeline_data = pd.read_csv('timeline.txt')

grouped = timeline_data.groupby('Instrument')
grouped = [grouped.get_group(x) for x in grouped.groups]

for level, frame in enumerate(grouped):
    df = {}
    df['name'] = frame['Instrument'].values[0]
    df['data'] = []
    
    for row in frame.itertuples():
        block = {}
        block['x'] = level
        st = dt.strptime(row[2], '%Y-%m-%d %H:%M')
        st = int((st-dt(1970,1,1)).total_seconds()*1000)
        en = dt.strptime(row[3], '%Y-%m-%d %H:%M')
        en = int((en-dt(1970,1,1)).total_seconds()*1000)
        block['low'] = st
        block['high'] = en
        block['mode'] = row[4]
        block['power'] = row[5]
        block['data_rate'] = row[6]
        df['data'].append(block)
        
    data['series'].append(df)

In [25]:
json_data = "new Highcharts.Chart(%s);" % json_encode(data)

In [26]:
display(HTML("""<div id="{chart_id}"</div>
<script type="text/javascript">{data}</script>""".format(chart_id="bepitimeline", data=json_data)))



In [ ]: