python - 在mpld3中如何使红线可拖动?
问题描述
我正在尝试使用鼠标指针将红色垂直线沿垂直方向向右侧和左侧拖动,并且在释放时我想打印 x 轴值。我无法将 line_a 与 DragPlugin 类连接起来。我按照https://mpld3.github.io/examples/drag_points.html这段代码作为参考。
"""
Draggable Points Example
========================
This example shows how a D3 plugin can be created to make plot elements
draggable. A stopPropagation command is used to allow the drag behavior
and pan/zoom behavior to work in tandem.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import mpld3
from matplotlib import lines
from mpld3 import plugins, utils
class DragPlugin(plugins.PluginBase):
JAVASCRIPT = r"""
mpld3.register_plugin("drag", DragPlugin);
DragPlugin.prototype = Object.create(mpld3.Plugin.prototype);
DragPlugin.prototype.constructor = DragPlugin;
DragPlugin.prototype.requiredProps = ["id"];
DragPlugin.prototype.defaultProps = {}
function DragPlugin(fig, props){
mpld3.Plugin.call(this, fig, props);
mpld3.insert_css("#" + fig.figid + " path.dragging",
{"fill-opacity": "1.0 !important",
"stroke-opacity": "1.0 !important"});
};
DragPlugin.prototype.draw = function(){
var obj = mpld3.get_element(this.props.id);
var drag = d3.drag()
.on("drag", dragged)
obj.elements()
.data(obj.offsets)
.style("cursor", "default")
.call(drag);
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this).classed("dragging", true);
}
function dragged(d, i) {
d[0] = obj.ax.x.invert(d3.event.x);
d[1] = obj.ax.y.invert(d3.event.y);
d3.select(this)
.attr("transform", "translate(" + [d3.event.x,d3.event.y] + ")");
}
function dragended(d) {
d3.select(this).classed("dragging", false);
}
}
"""
def __init__(self, points):
if isinstance(points, mpl.lines.Line2D):
suffix = "pts"
else:
suffix = None
self.dict_ = {"type": "drag",
"id": utils.get_id(points, suffix)}
fig, ax = plt.subplots()
np.random.seed(0)
points = ax.plot(np.random.normal(size=20),
np.random.normal(size=20), 'or', alpha=0.5,
markersize=50, markeredgewidth=1)
line_a = lines.Line2D((0.5, 0.5), (-3, 3),
pickradius=5,
color="r",
linewidth=2)
ax.add_line(line_a)
ax.set_title("Click and Drag", fontsize=18)
plugins.connect(fig, DragPlugin(points[0]))
plugins.connect(fig, DragPlugin(line_a))
mpld3.show()
请指导我如何实现用户可以使用鼠标指针垂直拖动红线标记并在释放鼠标时获取其位置的代码?
解决方案
推荐阅读
- android - android onActivityResult 没有在 Fragment 中被调用
- sql - SQL聚合函数选择唯一值
- java - 用于提供唯一 ID 的 Java 抽象类不起作用 - 所有对象都具有相同的 ID
- java - 在 GCP 中的 MYSQL DB 中批量插入
- javascript - React中图像上的CSS关键帧动画
- javascript - Express - POST 和 PUT 的 400 错误请求
- azure - Azure 数据工厂 - 如何使用空值初始化变量
- excel - VB循环代码根据另一个单元格值删除单元格范围
- pfsense - 路由问题?纳特问题?
- html - 如何在 Angular 中排除 nod_module 样式的 css?