簡體   English   中英

MPLD3:條形圖的標簽信息

[英]MPLD3: label information of barplot

我正在嘗試擴展此處提供的示例:

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))

我的目的是做相同的事情(單擊對象時顯示標簽),但是用barplot而不是scatterplot。

它不適用於相同的Javascript代碼:

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))

但是,我可以獲得其中一種工作行為。 例如,使用plugins.connect(fig, ClickInfo(bars[0])) ,單擊第一欄將觸發警報Javascript代碼。

題:

我如何對每個酒吧都具有相同的行為?

此外,由於我對D3和Javascript經驗不足,因此簡短解釋代碼的工作方式將非常有幫助。 也歡迎任何學習資源,因為我找不到MPLD3教程。

我遇到了同樣的問題,並擴展了帶有浮動標簽的堆積條形圖的答案,您可以在此處找到:

http://nbviewer.ipython.org/gist/Iggam/416520098460b057c208

該代碼可以在這里找到:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mpld3
from mpld3 import plugins, utils

class BarLabelToolTip(plugins.PluginBase):    
    JAVASCRIPT = """
    mpld3.register_plugin("barlabeltoolTip", BarLabelToolTip);
    BarLabelToolTip.prototype = Object.create(mpld3.Plugin.prototype);
    BarLabelToolTip.prototype.constructor = BarLabelToolTip;
    BarLabelToolTip.prototype.requiredProps = ["ids","labels"];
    BarLabelToolTip.prototype.defaultProps = {
        hoffset: 0,
        voffset: 10,
        location: 'mouse'
    };
    function BarLabelToolTip(fig, props){
        mpld3.Plugin.call(this, fig, props);
    };

    BarLabelToolTip.prototype.draw = function(){
        var svg = d3.select("#" + this.fig.figid);
        var objs = svg.selectAll(".mpld3-path");
        var loc = this.props.location;
        var labels = this.props.labels

        test = this.fig.canvas.append("text")
            .text("hello world")
            .style("font-size", 72)
            .style("opacity", 0.5)
            .style("text-anchor", "middle")
            .attr("x", this.fig.width / 2)
            .attr("y", this.fig.height / 2)
            .style("visibility", "hidden");

        function mousemove(d) {
            if (loc === "mouse") {
                var pos = d3.mouse(this.fig.canvas.node())
                this.x = pos[0] + this.props.hoffset;
                this.y = pos[1] - this.props.voffset;
            }

            test
                .attr("x", this.x)
                .attr("y", this.y);
        };

        function mouseout(d) {
            test.style("visibility", "hidden")
        };

        this.props.ids.forEach(function(id, i) {


            var obj = mpld3.get_element(id);

            function mouseover(d) {
                test.style("visibility", "visible")
                    .style("font-size", 24)
                    .style("opacity", 0.7)
                    .text(labels[i])
            };

            obj.elements().on("mouseover", mouseover.bind(this))

        });

       objs.on("mousemove", mousemove.bind(this)) 
           .on("mouseout", mouseout.bind(this));     

    }       
    """
    def __init__(self, ids, labels=None, location="mouse"):

        self.dict_ = {"type": "barlabeltoolTip",
                      "ids": ids,
                      "labels": labels,
                      "location": location}

fig, ax = plt.subplots()
x = range(0,10)
y = np.random.rand(10)
bars = ax.bar(x, y)

labels = [round(bar.get_height(),2) for bar in bars]
ids = [utils.get_id(bar) for bar in bars]

plugins.connect(fig, BarLabelToolTip(ids, labels))

您走在正確的軌道上。 這是一種使您工作的方法:

from mpld3 import utils, plugins

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 = ["ids"];
    function ClickInfo(fig, props){
        mpld3.Plugin.call(this, fig, props);
    };

    ClickInfo.prototype.draw = function(){
        this.props.ids.forEach(function(id, i) {
            var obj = mpld3.get_element(id);
            obj.elements().on("mousedown",
                              function(d){alert("clicked on bar[" + i + "]");});
                              });
    }
    """
    def __init__(self, bars):
        self.dict_ = {"type": "clickinfo",
                      "ids": [utils.get_id(bar) for bar in bars]}
x = range(0,10)
y = np.random.rand(10)

fig, ax = plt.subplots()
bars = ax.bar(x, y)

plugins.connect(fig, ClickInfo(bars))

您可以在此處查看它的運行情況 也許其他人將有時間用更多關於代碼如何工作的解釋來擴展此答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM