Snippets

Adam Labadorf ipython d3coffeescript magic

Created by Adam Labadorf last modified Adam Labadorf
#https://bitbucket.org/snippets/adamlabadorf/x684a/ipython-d3coffeescript-magic
import argparse
import inspect
import os
from IPython.core.magic import register_cell_magic
from IPython.display import Javascript,display
from json import dumps
@register_cell_magic
def d3coffeescriptmagic(line, cell):
    'my cell magic'
    parser = argparse.ArgumentParser()
    parser.add_argument('-v','--d3version',choices=['3','4']
            ,help='d3 version',default='4')
    parser.add_argument('var',nargs='*')
    args = parser.parse_args(line.split())

    stack = inspect.stack()
    def find_stack_var(varname) :
      # walk up stack to look for data vars
      for st in stack :
        #pprint(st[0].f_locals)
        if varname in st[0].f_locals :
          print(st[0])
          return st[0].f_locals[varname]

    # load the data variables passed on the line into JS
    data_var_js = 'var data = {};'
    for data_var in args.var :
        data = find_stack_var(data_var)
        if data :
          data_var_js += 'data["{}"] = {};'.format(data_var,dumps(data))

    # scan for #%% lines that include additional commands
    cell_lines = cell.split('\n')
    for i in range(len(cell_lines)) :
        line = cell_lines[i]
        if line.startswith('#%%include') :
            pieces = line.strip().split(' ')
            fn = pieces[1]
            if os.path.exists(fn) :
                cell_lines[i] = open(fn).read()
            else :
                cell_lines[i] = ('console.log "{} not found in d3coffeescript '
                                 'magic {}:#%%include"\n').format(fn,i)

    cell = '\n'.join(cell_lines)

    # the import is different for d3 v3 vs v4
    if args.d3version == '3' :
        js_tmpl = '''
        require.config({{
            paths: {{
                d3: '//d3js.org/d3.v3.min'
                ,underscore: '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min'
                ,coffee: '//coffeescript.org/v1/browser-compiler/coffee-script'
            }}
        }});
        require(['d3','underscore','coffee'],function(d3,_,coffee) {{
            element.innerText = coffee.compile({cell},{{bare: true}});
            element.innerText = '{data}'+element.innerText;
            eval(element.innerText);
        }});
        '''
    elif args.d3version == '4' :
         js_tmpl = '''
        require.config({{
            paths: {{
                d3: '//d3js.org/d3.v4.min'
                ,underscore: '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min'
                ,coffee: '//coffeescript.org/v1/browser-compiler/coffee-script'
            }}
        }});
        require(['d3','underscore','coffee'],function(d3,_,coffee) {{
            element.innerText = coffee.compile({cell},{{bare: true}});
            element.innerText = '{data}'+element.innerText;
            eval(element.innerText);
        }});
        '''
    js = js_tmpl.format(data=data_var_js,
           cell=dumps(cell)
           )
    return Javascript(js)

def d3_csv_parse(data) :
    header = data[0]
    parsed_data = [dict(zip(header,_)) for _ in data[1:]]
    return parsed_data

def pandas_to_d3(df) :
    data = []
    for _,r in df.iterrows() :
        data.append(r.to_dict())
    return data
#COMMIT removed print statement

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.