To visualize a 3D point cloud and add a widget for rotation in a Jupyter notebook using matplotlib, you can use the mpl_toolkits.mplot3d module for 3D plotting and ipywidgets for interactive widgets. Below is a step-by-step guide to achieve this:
Install Required Packages:
Ensure you have matplotlib and ipywidgets installed. You can install them using pip if you haven't already:
bash
pip install matplotlib ipywidgets
Import Necessary Libraries:
python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from ipywidgets import interact, FloatSlider
from IPython.display import display
Generate or Load Your 3D Point Cloud Data:
For demonstration, let's generate some random 3D points.
python
np.random.seed(42)
points = np.random.rand(100, 3) # 100 random points in 3D
Define a Function to Plot the 3D Point Cloud with Rotation:
Putting it all together, here’s the complete code:
python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from ipywidgets import interact, FloatSlider
# Generate random 3D points
np.random.seed(42)
points = np.random.rand(100, 3) # 100 random points in 3D
# Function to plot the 3D point cloud
def plot_point_cloud(elev=30, azim=30):
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:, 0], points[:, 1], points[:, 2], c='b', marker='o')
ax.view_init(elev=elev, azim=azim)
plt.show()
# Create interactive widgets for rotation
interact(plot_point_cloud, elev=FloatSlider(min=0, max=90, step=0.1, value=30),
azim=FloatSlider(min=0, max=360, step=0.1, value=30))
When you run this code in a Jupyter notebook, it will display a 3D plot of the point cloud with two sliders below it. You can use these sliders to interactively rotate the plot by changing the elevation and azimuth angles.