is there a way to read out the zoom level of an mpld3 plot, i.e. the range of the visible x- and y-axis? I tried to use d3.behavior.zoom, but I don't know how I can get the zoom behavior of my mpld3 plot.
Asked
Active
Viewed 988 times
1 Answers
1
You can make a mpld3
plugin do this using the pattern I developed for interactively adding callouts to scatter plots. This is a lot simpler, actually, so it is a good example of a simple-but-useful plugin:
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()
Here is a Jupyter Notebook version, if you want to play around.

Abraham D Flaxman
- 2,969
- 21
- 39
-
Thanks a lot! I finally found the time to try it and it works like a charm :-) – CWelling Jan 26 '16 at 08:36