{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Animated 3D random walk\n\nOutput generated via `matplotlib.animation.Animation.to_jshtml`.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.animation as animation\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\ndef random_walk(num_steps, max_step=0.05):\n    \"\"\"Return a 3D random walk as (num_steps, 3) array.\"\"\"\n    start_pos = np.random.random(3)\n    steps = np.random.uniform(-max_step, max_step, size=(num_steps, 3))\n    walk = start_pos + np.cumsum(steps, axis=0)\n    return walk\n\n\ndef update_lines(num, walks, lines):\n    for line, walk in zip(lines, walks):\n        line.set_data_3d(walk[:num, :].T)\n    return lines\n\n\n# Data: 40 random walks as (num_steps, 3) arrays\nnum_steps = 30\nwalks = [random_walk(num_steps) for index in range(40)]\n\n# Attaching 3D axis to the figure\nfig = plt.figure()\nax = fig.add_subplot(projection=\"3d\")\n\n# Create lines initially without data\nlines = [ax.plot([], [], [])[0] for _ in walks]\n\n# Setting the Axes properties\nax.set(xlim3d=(0, 1), xlabel='X')\nax.set(ylim3d=(0, 1), ylabel='Y')\nax.set(zlim3d=(0, 1), zlabel='Z')\n\n# Creating the Animation object\nani = animation.FuncAnimation(\n    fig, update_lines, num_steps, fargs=(walks, lines), interval=100)\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. tags:: component: animation, plot-type: 3D\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}