获取mpld3绘图的缩放级别

时间:2016-01-14 13:13:45

标签: mpld3

有没有办法读出mpld3图的缩放级别,即可见x轴和y轴的范围? 我尝试使用d3.behavior.zoom,但我不知道如何获得mpld3绘图的缩放行为。

1 个答案:

答案 0 :(得分:1)

您可以使用我为interactively adding callouts to scatter plots开发的模式制作mpld3插件。实际上,这更简单,因此它是一个简单但有用的插件的一个很好的例子:

import matplotlib.pyplot as plt, mpld3
%matplotlib inline

class ZoomSizePlugin(mpld3.plugins.PluginBase):
    JAVASCRIPT = r"""
    // little save icon
    var my_icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gUTDC0v7E0+LAAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAa0lEQVQoz32QQRLAIAwCA///Mz3Y6cSG4EkjoAsk1VgAqspecVP3TTIA6MHTQ6sOHm7Zm4dWHcC4wc3hmVzT7xEbYf66dX/xnEOI7M9KYgie6qvW6ZH0grYOmQGOxzCEQn8C5k5mHAOrbeIBWLlaA3heUtcAAAAASUVORK5CYII=";

    // create plugin
    mpld3.register_plugin("zoomSize", ZoomSizePlugin);
    ZoomSizePlugin.prototype = Object.create(mpld3.Plugin.prototype);
    ZoomSizePlugin.prototype.constructor = ZoomSizePlugin;
    ZoomSizePlugin.prototype.requiredProps = [];
    ZoomSizePlugin.prototype.defaultProps = {}

    function ZoomSizePlugin(fig, props){
        mpld3.Plugin.call(this, fig, props);

        // create save button
        var SaveButton = mpld3.ButtonFactory({
            buttonID: "save",
            sticky: false,
            onActivate: function(){save_zoom(fig);}.bind(this),
            icon: function(){return my_icon;},
        });
        this.fig.buttons.push(SaveButton);
    };

    function save_zoom(fig) {
      var ax= fig.axes[0],
          extent = "";
      extent = extent + "left=" + ax.x.invert(0);
      extent = extent + ", right=" + ax.x.invert(ax.width);
      extent = extent + ", bottom=" + ax.y.invert(ax.height);
      extent = extent + ", top=" + ax.y.invert(0);

      prompt("Copy extent of zoomed axis:", extent);
    }

    """

    def __init__(self):
        self.dict_ = {"type": "zoomSize"}

plt.plot([3,1,4,1,5,9,2,6,5,3,5,8], 'ks-', mew=1, mec='w')
mpld3.plugins.connect(plt.gcf(), ZoomSizePlugin())
mpld3.display()

对我来说,它看起来像这样: enter image description here

这是a Jupyter Notebook version, if you want to play around