Published
Edited
May 14, 2019
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
html0 = {return html`
<svg id="graph0"></svg>
<div>
<button id='upd1'>update 1</button>
<button id='upd2'>update 2</button>
<button id='res0'>reset:</button>
<input type='text' id='inp0'/>
</div>
`}
Insert cell
{html0, __BRYTHON__ //wait for html0 and __BRYTHON__
py`
from browser import window, document
print('\n Brython', window.__BRYTHON__.__MAGIC__)
d3 = window.d3

svg = d3.select("#graph0")
svg\
.attr("width", 340)\
.attr("height", 300)\
.style("border","1px dotted black")\

btn1 = document['upd1']
btn2 = document['upd2']
btn0 = document['res0']
inp0 = document['inp0']

btn1.title='move cx'
colors2 = ['DarkBlue','Aqua']
btn2.title=', '.join(colors2)
inp0.value=', '.join(['blue','red','yellow'])

circles = svg.select("g.circlesGroup")
if (circles.empty()):
circles = svg.append("g")
circles.classed("circlesGroup", True);

def init(ev):
inp = inp0.value
btn0.title = inp + ' - centered'
colorsN = inp.split(',')
n = len(colorsN)

circles.selectAll("circle")\
.data(colorsN)\
.join("circle")\
.attr("stroke", "fuchsia")\
.attr("stroke-width", 2.5)\
.attr("fill",lambda d, *_: d)\
.attr("r", lambda d, i, *_: (n-i)*20)\
.attr("cx", 170)\
.attr("cy", 150)\

init(None)

#update data (and auto-rearrange svg)
def update1(ev):
circles.selectAll("circle")\
.attr("cx", lambda d, i, *_:(170-i*25))\

def update2(ev): #reduce numb. of circles
circles.selectAll("circle")\
.data(colors2)\
.join("circle")\
.attr("fill",lambda d, *_: d)\

def inputEnterKey(ev):
if (ev.keyCode == 13):
ev.preventDefault()
if (ev.type == "keydown"):
init(ev)

def rebind(elt, evt_name, handler):
if elt.events(evt_name): elt.unbind(evt_name) #? or elt.unbind(evt_name, handler)
elt.bind(evt_name, handler)

rebind(btn1, "click", update1)
rebind(btn2, "click", update2)
rebind(btn0, "click", init)
rebind(inp0,"keydown",inputEnterKey)
rebind(inp0, "keyup", inputEnterKey)

print('.')`; return 'd3 in python code'}
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more