Using d3.select on a python-generated object

325 Views Asked by At

I'm using mpld3 to create a graph in a web app. I want to allow the user to drag the orange line.

enter image description here

I explicitly want to code this drag-and-drop behavior directly in d3.js, because d3.js allows me to set restrictions on the drag behavior (specifically I want to allow only horizontal drag, as shows in this JSFiddle.)

I am having trouble selecting the orange line element. I am getting its ID with mpld3.utils.get_id(), but passing this id on the JS side to either d3.select() or to mpld3.get_element() does not work.

import mpld3
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1,1,20)
fig, ax = plt.subplots()
ax.plot(x,x**3)
line = ax.plot([0,0],[-1,0])

js = '''
<script src="https://d3js.org/d3.v4.min.js"></script>
'''

html = mpld3.fig_to_html(fig)

print(mpld3.utils.get_id(line)) # gives something like 'el68722312816129664'

with open('pured3_output.html', 'w') as f:
    f.write(html+js)

After opening pured3_output.html in the browser, I type this in the browser console:

>>> mpld3.get_element('el68722312816129664')
null
>>> d3.select('#el68722312816129664')
Selection {_groups: Array(1), _parents: Array(1)}

I don't know what it's returning but it's clearly not the right thing, because, d3.select('#el68722312816129664').remove() doesn't do anything.

I'm not particularly attached to using mpld3, compared to other packages built on top of d3.js, such as Plotly. I am using mpld3 so far because it seems simple and lightweight. (By the way, Plotly did not allow me to do what I wanted without touching the d3.js.). If this question is for some reason hard to solve in mpld3 (I don't see why it should be), please let me know how you would do it with a different package.

0

There are 0 best solutions below