2

I would like to interact with matplotlib figures 2D as well as 3D in google-collaboratory. I can't zoom, rotate or do any kind of interaction using this normal code.

import numpy as np
from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import style
style.use("ggplot")

centers = [[1,1,1],[5,5,5],[3,10,10]]

X, _ = make_blobs(n_samples = 100, centers = centers, cluster_std = 1.5)

ms = MeanShift()
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_

print(cluster_centers)
n_clusters_ = len(np.unique(labels))
print("Number of estimated clusters:", n_clusters_)

colors = 10*['r','g','b','c','k','y','m']
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for i in range(len(X)):
    ax.scatter(X[i][0], X[i][1], X[i][2], c=colors[labels[i]], marker='o')

ax.scatter(cluster_centers[:,0],cluster_centers[:,1],cluster_centers[:,2],
            marker="x",color='k', s=150, linewidths = 5, zorder=10)


iheathers
  • 371
  • 6
  • 13
  • 1
    Hi and welcome to SO! I've never used colab but I suppose if you just use an interactive matplotlib backend `%matplotlib notebook` it'll work, as suggested in this post: https://stackoverflow.com/questions/44329068/jupyter-notebook-interactive-plot-with-widgets – Aleksander Lidtke Jun 09 '20 at 06:24
  • Additionally, this [colab reference guide](https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/04.12-Three-Dimensional-Plotting.ipynb) covers 3d plotting and combined with the `%matplotlib notebook` adjustment should do the trick. – jwho Jun 09 '20 at 14:17
  • I actually want to rotate, zoom in , pan in and pan out just like when i run the above code in python idle, where it provides new window for the figure. For eg. at 7:24 in this video the user is actually rotating or zooming in and out. Can i achieve that in colab? https://www.youtube.com/watch?v=Zv9a_wMJMe4 – iheathers Jun 09 '20 at 15:51

1 Answers1

4

I know is more than a year later but I hope it helps someone out there.

I can't believe a single link solves everything. https://www.geeksforgeeks.org/make-3d-interactive-matplotlib-plot-in-jupyter-notebook/

To adapt it to colab you would need

!pip install ipympl

and

# TO SHOW INTERACTIVE PLOT
%matplotlib widget
from google.colab import output
output.enable_custom_widget_manager()

And that's basically it (: any plt.plot(...) or ax.scatter(...) would now be interactive.

KevinC-md
  • 41
  • 4
  • 1
    great answer! couldn't believe it was this easy (after searching so many non-helpful workarounds) – BAM Apr 24 '23 at 06:57