2019-06-13
Graphically select geometric objects in a Jupyter/iPython notebook
stackoverflow
Question

The interoperability between Shapely and Jupyter/iPython is nice. I can do cool stuff like create a bunch of geometric shapes and view them in the notebook:

some_nodes = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]
some_boxes = []
some_boxes.append([some_nodes[0], some_nodes[3], some_nodes[4], some_nodes[1]])
some_boxes.append([some_nodes[1], some_nodes[4], some_nodes[5], some_nodes[2]])

from shapely.geometry import MultiPolygon, Polygon
MultiPolygon([Polygon(box) for box in some_boxes])

...and Jupyter will show me this:

Jupyter_Shapely_output

Now THAT is cool! It has been especially useful to me for quickly viewing and editing, for example, polygons that make up 2D finite element meshes.

Sadly, the images produced are just static SVG graphics; there's no interaction built in. It would be helpful to be able to select a subset of those objects in the image using this same graphical interface in iPython.

More specifically, I'd like to be able to create a list and add some of the displayed polygons to it by, for example, clicking/selecting them, or dragging a lasso/box around them, and also perhaps remove them when clicking a second time.

I've looked into trying to do this with matplotlib or javascript and although I've had some initial success it's probably the kind of project that is out of my depth at my current level of knowledge/skill.

Since Jupyter is a somewhat sprawling tool with lots of features that I am probably not aware of, I am wondering if there are already existing solutions out there for interaction of this sort in the context of a Jupyter notebook?

UPDATE: It looks like I'm going to have to create something myself. Happily, this tutorial is going to make that a LOT easier.

UPDATE #2: It appears that Bokeh is a library much more suited for this purpose. I believe I am going to abandon the idea of creating custom Jupyter widgets and create an app using Bokeh widgets and interactions instead. Such an app can be used in a Jupyter notebook, but also elsewhere.

UPDATE #3: I ended up using the jupyter widget system anyway. Added my own answer showing a proof of concept.

Answer
1

Bokeh and Plotly are two interactive python visualization libraries with support for spatial data. you can check out some examples (1, 2) to see if this is what you are looking for. This repository contains some very cool examples of 2D and 3D visualizations which you can run right in your jupyter notebook. You can also use GeoPandas and Folium to create fully interactive maps (here is a great tutorial).

Graphically select geometric objects in a Jupyter/iPython notebook
See more ...