I'm trying to extend the example provided here:
from mpld3 import utils
class ClickInfo(plugins.PluginBase):
"""Plugin for getting info on click"""
JAVASCRIPT = """
mpld3.register_plugin("clickinfo", ClickInfo);
ClickInfo.prototype = Object.create(mpld3.Plugin.prototype);
ClickInfo.prototype.constructor = ClickInfo;
ClickInfo.prototype.requiredProps = ["id"];
function ClickInfo(fig, props){
mpld3.Plugin.call(this, fig, props);
};
ClickInfo.prototype.draw = function(){
var obj = mpld3.get_element(this.props.id);
obj.elements().on("mousedown",
function(d, i){alert("clicked on points[" + i + "]");});
}
"""
def __init__(self, points):
self.dict_ = {"type": "clickinfo",
"id": utils.get_id(points)}
fig, ax = plt.subplots()
points = ax.scatter(np.random.rand(50), np.random.rand(50),
s=500, alpha=0.3)
plugins.connect(fig, ClickInfo(points))
My purpose is to do the same thing (display label when the object is clicked) but with barplot instead of scatterplot.
It doesn't work with the same Javascript code:
from mpld3 import utils
class ClickInfo(plugins.PluginBase):
"""Plugin for getting info on click"""
JAVASCRIPT = """
mpld3.register_plugin("clickinfo", ClickInfo);
ClickInfo.prototype = Object.create(mpld3.Plugin.prototype);
ClickInfo.prototype.constructor = ClickInfo;
ClickInfo.prototype.requiredProps = ["id"];
function ClickInfo(fig, props){
mpld3.Plugin.call(this, fig, props);
};
ClickInfo.prototype.draw = function(){
var obj = mpld3.get_element(this.props.id);
obj.elements().on("mousedown",
function(d, i){alert("clicked on bar[" + i + "]");});
}
"""
def __init__(self, bars):
self.dict_ = {"type": "clickinfo",
"id": utils.get_id(bars)}
x = range(0,10)
y = np.random.rand(10)
fig, ax = plt.subplots()
bars = ax.bar(x, y)
plugins.connect(fig, ClickInfo(bars))
However, I can obtain a working behavior for one of the bar. For example, with plugins.connect(fig, ClickInfo(bars[0]))
, a click on the first bar will trigger the alert Javascript code.
Question:
How can I have the same behavior for each bar ?
Moreover, as I am inexperienced with D3 and Javascript a short explanation of how the code works would be very helpful. Any ressource to learn is also welcome as I can't find MPLD3 tutorials.
You are on the right track. Here is a way to make what you have work:
You can see it in action here. Perhaps someone else will have time to extend this answer with more of an explanation of how the code works.