#https://bitbucket.org/snippets/adamlabadorf/x684a/ipython-d3coffeescript-magicimportargparseimportinspectimportosfromIPython.core.magicimportregister_cell_magicfromIPython.displayimportJavascript,displayfromjsonimportdumps@register_cell_magicdefd3coffeescriptmagic(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()deffind_stack_var(varname):# walk up stack to look for data varsforstinstack:#pprint(st[0].f_locals)ifvarnameinst[0].f_locals:print(st[0])returnst[0].f_locals[varname]# load the data variables passed on the line into JSdata_var_js='var data = {};'fordata_varinargs.var:data=find_stack_var(data_var)ifdata:data_var_js+='data["{}"] = {};'.format(data_var,dumps(data))# scan for #%% lines that include additional commandscell_lines=cell.split('\n')foriinrange(len(cell_lines)):line=cell_lines[i]ifline.startswith('#%%include'):pieces=line.strip().split(' ')fn=pieces[1]ifos.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 v4ifargs.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); }}); '''elifargs.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))returnJavascript(js)defd3_csv_parse(data):header=data[0]parsed_data=[dict(zip(header,_))for_indata[1:]]returnparsed_datadefpandas_to_d3(df):data=[]for_,rindf.iterrows():data.append(r.to_dict())returndata#COMMIT removed print statement
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.