首页 > 解决方案 > 在 python 生成的对象上使用 d3.select

问题描述

我正在使用 mpld3 在 Web 应用程序中创建图表。我想允许用户拖动橙色线。

在此处输入图像描述

我明确地想直接在 d3.js 中编写这种拖放行为,因为 d3.js 允许我对拖动行为设置限制(特别是我希望只允许水平拖动,如此 JSFiddle 所示。)

我无法选择橙色线元素。我用 获取它的 ID mpld3.utils.get_id(),但是在 JS 端将此 id 传递给d3.select()or 或 tompld3.get_element()不起作用。

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)

在浏览器中打开后pured3_output.html,我在浏览器控制台中输入:

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

我不知道它会返回什么,但这显然不是正确的,因为d3.select('#el68722312816129664').remove()它什么也没做。

与基于 d3.js 构建的其他软件包(例如 Plotly)相比,我并不特别喜欢使用 mpld3。到目前为止,我正在使用 mpld3,因为它看起来简单且轻量级。(顺便说一句,Plotly 不允许我在不接触 d3.js 的情况下做我想做的事。)。如果这个问题由于某种原因在 mpld3 中难以解决(我不明白为什么应该这样),请告诉我你将如何使用不同的包来解决。

标签: pythond3.jsplotmpld3

解决方案


推荐阅读