0

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

4

1 回答 1

1

您可以使用我为交互式添加标注到散点图而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()

对我来说,它看起来像这样: 在此处输入图像描述

这是一个 Jupyter Notebook 版本,如果你想玩的话

于 2016-01-14T21:40:26.277 回答