Plotly for Mechanics#

Welcome to the world of interactive data visualization in mechanics! Plotly, a powerful graphing library for Python, offers an exciting way to visualize mechanical concepts and simulations. This tutorial will introduce you to the basics of Plotly and show you how to create interactive graphs that can enhance your understanding of mechanics.

Why Plotly for Mechanics?#

Mechanics, the branch of physics dealing with motion and forces, often involves complex concepts that are best understood through visual representation. Plotly steps in as a dynamic tool to visualize these concepts, making it easier to grasp relationships, patterns, and behaviors in mechanical systems.

Key Features:

  • Interactive Graphs: Zoom, pan, and hover to explore the data in more detail.

  • Versatile Plot Types: From simple line and scatter plots to complex 3D models.

  • Customizable and Aesthetic: Make your graphs informative and visually appealing.

Getting Started with Plotly#

Installation#

To begin, you need to install Plotly. If you haven’t installed it yet, you can do so using pip:

pip install plotly

Note

No need to follow this step, if you are using Google Colab

Basic Plot with Plotly#

Let’s start by creating a simple line graph, which could represent a basic mechanical relationship, like displacement vs. time.

Breath Out!

Don’t worry about the code. We’ll go through it later. just copy and paste it on your colab cell and run it now!

This code will generate an interactive line graph showing the relationship between time and displacement as below. Hover on the data points and see the info.

[2]:
import plotly.graph_objects as go

# Sample data
time = [0, 1, 2, 3, 4, 5]  # Time in seconds
displacement = [0, 1, 4, 9, 16, 25]  # Displacement in meters (squared relationship)

# Create the figure
fig = go.Figure(data=go.Scatter(x=time, y=displacement, mode='lines+markers'))

# Add title and labels
fig.update_layout(title='Displacement vs. Time',
                  xaxis_title='Time (s)',
                  yaxis_title='Displacement (m)')

# Show the plot
fig.show()

Advanced Plotting: 3D Visualization#

Plotly excels in creating 3D visualizations, which can be particularly useful in mechanics for understanding more complex spatial relationships.

Imagine visualizing the trajectory of a projectile in three-dimensional space.This 3D plot dynamically illustrates the trajectory, allowing for a comprehensive view of the motion in space.

Use your curser to rotate. Try zooming in and zooming out features!

[3]:
import numpy as np

# Sample data for projectile motion
t = np.linspace(0, 10, 100)  # Time
x = t  # X position (linear)
y = t**2  # Y position (quadratic)
z = t**3  # Z position (cubic)

# Create 3D figure
fig = go.Figure(data=[go.Scatter3d(x=x, y=y, z=z, mode='lines')])

# Add title and labels
fig.update_layout(title='3D Trajectory of a Projectile',
                  scene=dict(
                      xaxis_title='X Axis',
                      yaxis_title='Y Axis',
                      zaxis_title='Z Axis')
                  )

# Show the plot
fig.show()

Adding Animation#

One of the most exciting features of Plotly is its ability to create animations. This is incredibly useful in mechanics, where understanding the evolution of a system over time is often crucial. Let’s dive into how you can add animation to your graphs to bring mechanical concepts to life.

Let’s create a simple animated graph to illustrate a concept in mechanics, such as a bouncing ball.

[4]:
import plotly.graph_objects as go
import numpy as np

# Sample data: Simple harmonic motion for a bouncing ball
frames = 30
time = np.linspace(0, 2 * np.pi, frames)
position = np.abs(np.sin(time))  # Absolute value of sine wave

# Create the figure
fig = go.Figure(
    data=[go.Scatter(x=[0], y=[position[0]], mode="markers")],
    layout=go.Layout(
        xaxis=dict(range=[-1, 1], autorange=False),
        yaxis=dict(range=[0, 1], autorange=False),
        title="Bouncing Ball Animation"
    ),
    frames=[go.Frame(data=[go.Scatter(x=[0], y=[position[k]])])
            for k in range(frames)]
)

# Add animation controls
fig.update_layout(updatemenus=[dict(
    type="buttons",
    buttons=[dict(label="Play",
                  method="animate",
                  args=[None, {"frame": {"duration": 100, "redraw": True}}]),
             dict(label="Pause",
                  method="animate",
                  args=[[None], {"frame": {"duration": 0, "redraw": False}}])]
)])

# Show the plot
fig.show()

This introduction has just scratched the surface of what’s possible with Plotly in the context of mechanics. As you delve deeper into mechanics simulations, you’ll find Plotly an invaluable tool for bringing data to life and gaining deeper insights into mechanical phenomena.

Remember

The best way to learn is by doing. Experiment with different types of graphs, play around with the settings, and visualize different mechanical concepts to see how Plotly can enhance your learning and research in mechanics. Happy plotting!