{"spec_id":"line-3d-trajectory","library":"pygal","language":"python","code":"\"\"\" anyplot.ai\nline-3d-trajectory: 3D Line Plot for Trajectory Visualization\nLibrary: pygal 3.1.3 | Python 3.14.10\nQuality: 87/100 | Updated: 2026-11-08\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport pygal\nfrom pygal.style import Style\nfrom scipy.integrate import solve_ivp\n\n\n# Theme tokens (see prompts/default-style-guide.md \"Background\" + \"Theme-adaptive Chrome\")\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\n\n# Imprint palette (see prompts/default-style-guide.md \"Categorical Palette\")\nIMPRINT_PALETTE = (\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\")\n\n# Columns: set these to your table's column names, rows in path order\nX = \"X\"  # role: x\nY = \"Y\"  # role: y\nZ = \"Z\"  # role: z\nTIME = \"Elapsed time (model time units)\"  # role: color\n\n# Data: Lorenz attractor trajectory (deterministic chaotic ODE, no randomness);\n# replace this block with your own table, for example df = pd.read_csv(\"trajectory.csv\")\nsigma, rho, beta = 10.0, 28.0, 8.0 / 3.0\ntimes = np.linspace(0.0, 30.0, 4000)  # 0.0075 time units per point keeps the fast outer loops smooth\nsolution = solve_ivp(\n    lambda t, s: [sigma * (s[1] - s[0]), s[0] * (rho - s[2]) - s[1], s[0] * s[1] - beta * s[2]],\n    (times[0], times[-1]),\n    [0.0, 1.0, 1.05],\n    t_eval=times,\n    rtol=1e-9,\n    atol=1e-9,\n)\ndf = pd.DataFrame({X: solution.y[0], Y: solution.y[1], Z: solution.y[2], TIME: solution.t})\n\n# Plot: orthographic view from elevation 20°, azimuth -45° (world x, y, z → screen u, v), so the\n# two wings sit side by side; pygal has no 3D chart type, so axes and ticks are projected the same way\ntrajectory = df[[X, Y, Z]].to_numpy(dtype=float)\nelapsed = df[TIME].to_numpy(dtype=float)\nnum_points = len(df)\nELEV, AZIM = np.radians(20), np.radians(-45)\nPROJ = np.array(\n    [[np.cos(AZIM), -np.sin(AZIM), 0.0], [np.sin(AZIM) * np.sin(ELEV), np.cos(AZIM) * np.sin(ELEV), np.cos(ELEV)]]\n)\nscreen = trajectory @ PROJ.T  # a row with a missing value projects to NaN and breaks the line there\n\n# Box around the path in world units; X and Y run along its front floor edges, Z up its left corner.\n# One shared tick step (1, 2 or 5 × 10^k) for at most eight ticks on the longest axis keeps the box at equal scale\nlo_world, hi_world = np.nanmin(trajectory, axis=0), np.nanmax(trajectory, axis=0)\nspan = (hi_world - lo_world).max()\nraw_step = (span if span > 0 else 1.0) / 8  # a single point still gets a unit box\nmagnitude = 10 ** np.floor(np.log10(raw_step))\nTICK = magnitude * min((m for m in (1, 2, 5, 10) if m * magnitude >= raw_step))\n(x0, y0, z0), (x1, y1, z1) = np.floor(lo_world / TICK) * TICK, np.ceil(hi_world / TICK) * TICK\ntick_len = 0.03 * (x1 - x0 + y1 - y0)\ngap = 2.8 * tick_len\nout_x, out_y = np.array([0.0, -1.0, 0.0]), np.array([1.0, 0.0, 0.0])  # outward from the X and Y edges\nout_z = np.array([-1.0, -1.0, 0.0]) / np.sqrt(2)  # outward from the left corner, straight left on screen\nx_ticks, y_ticks, z_ticks = (np.arange(a, b + TICK / 2, TICK) for a, b in ((x0, x1), (y0, y1), (z0, z1)))\n\naxis_world = [[(x0, y0, z0), (x1, y0, z0)], [(x1, y0, z0), (x1, y1, z0)], [(x0, y0, z0), (x0, y0, z1)]]\ntick_world = (\n    [[(t, y0, z0), np.array((t, y0, z0)) + tick_len * out_x] for t in x_ticks]\n    + [[(x1, t, z0), np.array((x1, t, z0)) + tick_len * out_y] for t in y_ticks]\n    + [[(x0, y0, t), np.array((x0, y0, t)) + tick_len * out_z] for t in z_ticks]\n)\naxes, ticks = [], []\nfor segments, series in ((axis_world, axes), (tick_world, ticks)):\n    for segment in segments:\n        series += [tuple(p) for p in np.array(segment, dtype=float) @ PROJ.T] + [None]\n\ntext_world = (\n    # floor-edge labels sit farther out than Z's, so X's first label drops clear below the Z column\n    [(np.array((t, y0, z0)) + 1.7 * gap * out_x, f\"{t:g}\") for t in x_ticks]\n    + [(np.array((x1, t, z0)) + 1.7 * gap * out_y, f\"{t:g}\") for t in y_ticks]\n    + [(np.array((x0, y0, t)) + gap * out_z, f\"{t:g}\") for t in z_ticks]\n    + [(np.array(((x0 + x1) / 2, y0, z0)) + 3.0 * gap * out_x, X)]\n    + [(np.array((x1, (y0 + y1) / 2, z0)) + 3.0 * gap * out_y, Y)]\n    + [(np.array((x0, y0, z1)) + np.array((0.0, 0.0, 1.4 * gap)), Z)]\n)\ntext_screen = np.array([p for p, _ in text_world], dtype=float) @ PROJ.T\n\n# Canvas: equal screen units per pixel on both axes so the projection is not stretched.\n# pygal reserves `margin` on every side and `spacing + title_font_size` for the title, and pads\n# the plot box by 2% of each range\nWIDTH, HEIGHT, MARGIN, SPACING = 3200, 1800, 60, 30\nTITLE_FS, LABEL_FS = 66, 44\nextent = np.vstack([screen, text_screen])\npad = np.array([0.06, 0.03]) * (np.nanmax(extent, axis=0) - np.nanmin(extent, axis=0))\nlo, hi = np.nanmin(extent, axis=0) - pad, np.nanmax(extent, axis=0) + pad\nview_w, view_h = WIDTH - 2 * MARGIN, HEIGHT - 2 * MARGIN - (SPACING + TITLE_FS)\npx_per_unit = min(view_w / (hi[0] - lo[0]), view_h / (hi[1] - lo[1])) / 1.04\ncenter = (lo + hi) / 2\nhalf = np.array([view_w, view_h]) / px_per_unit / 2 / 1.04\n\n# Time key in the top right corner: a bar drawn in the line's own gradient, with its end values\nnum_segments = 30\nkey_len, key_top = 0.16 * 2 * half[0], center[1] + 0.9 * half[1]\nkey_x = np.linspace(center[0] + 0.85 * half[0] - key_len, center[0] + 0.85 * half[0], num_segments + 1)\nkey_text = [\n    ((key_x[0] + key_x[-1]) / 2, key_top, TIME),\n    (key_x[0], key_top - 2 * LABEL_FS / px_per_unit, f\"{np.nanmin(elapsed):.3g}\"),\n    (key_x[-1], key_top - 2 * LABEL_FS / px_per_unit, f\"{np.nanmax(elapsed):.3g}\"),\n]\nkey_y = key_top - 1.0 * LABEL_FS / px_per_unit\n\n# pygal prints a point's label value_font_size px right of it and 4/3 value_font_size px below it;\n# with value_font_size at 0.26 x the label size the centred text sits on its anchor\nshift = np.array([-0.26 * LABEL_FS, 0.0]) / px_per_unit\nlabels = [{\"value\": tuple(p + shift), \"label\": text} for p, (_, text) in zip(text_screen, text_world, strict=True)]\nlabels += [{\"value\": (x + shift[0], y), \"label\": text} for x, y, text in key_text]\n\n# imprint_seq gradient along time (brand green → blue): the path is split into segments of equal\n# point count that share their end points, so the line stays continuous; each segment's colour also\n# paints its step of the key bar. A point with a missing value becomes None, a break in the line\nstops = np.array([[int(h[i : i + 2], 16) for i in (1, 3, 5)] for h in (IMPRINT_PALETTE[0], IMPRINT_PALETTE[2])])\nbounds = np.linspace(0, num_points - 1, num_segments + 1).round().astype(int)\nsegments, gradient_colors = [], []\nfor i in range(num_segments):\n    r, g, b = np.round(stops[0] + (stops[1] - stops[0]) * i / (num_segments - 1)).astype(int)\n    gradient_colors.append(f\"rgba({r}, {g}, {b}, 0.85)\")\n    path = [tuple(p) if np.isfinite(p).all() else None for p in screen[bounds[i] : bounds[i + 1] + 1]]\n    segments.append(path + [None, (key_x[i], key_y), (key_x[i + 1], key_y)])\n\ncustom_style = Style(\n    background=PAGE_BG,\n    plot_background=PAGE_BG,\n    foreground=INK,\n    foreground_strong=INK,\n    foreground_subtle=INK_SOFT,\n    colors=(INK, INK_SOFT, INK_SOFT, *gradient_colors),\n    value_colors=(INK,) * (3 + num_segments),\n    opacity=1,\n    stroke_opacity=1,\n    stroke_opacity_hover=1,\n    stroke_width=3.5,  # the trajectory; axes, ticks and the key bar are set in the css below\n    title_font_size=TITLE_FS,\n    label_font_size=LABEL_FS,\n    major_label_font_size=LABEL_FS,\n    value_font_size=round(0.26 * LABEL_FS),\n    value_label_font_size=LABEL_FS,\n    tooltip_font_size=36,\n)\n\nchart = pygal.XY(\n    title=\"line-3d-trajectory · python · pygal · anyplot.ai\",\n    width=WIDTH,\n    height=HEIGHT,\n    style=custom_style,\n    margin=MARGIN,\n    spacing=SPACING,\n    show_legend=False,\n    show_x_labels=False,\n    show_y_labels=False,\n    xrange=(center[0] - half[0], center[0] + half[0]),\n    range=(center[1] - half[1], center[1] + half[1]),\n    print_labels=True,\n    print_values=False,\n    css=(\n        \"file://style.css\",\n        \"file://graph.css\",\n        \"inline:.text-overlay text.label { text-anchor: middle; }\",\n        \"inline:.serie-1 .line, .serie-2 .line { stroke-width: 2.5px !important; }\",\n        \"inline:.plot_title { font-weight: bold; }\",\n    ),\n)\n\n# Labels first, so their index is fixed for the css above; text is always drawn above the marks\nchart.add(\"Labels\", labels, stroke=False, dots_size=0)\nchart.add(\"Axes\", axes, show_dots=False, allow_interruptions=True)\nchart.add(\"Ticks\", ticks, show_dots=False, allow_interruptions=True)\nfor i, path in enumerate(segments):\n    chart.add(\n        f\"t = {elapsed[bounds[i]]:.3g}–{elapsed[bounds[i + 1]]:.3g}\", path, show_dots=False, allow_interruptions=True\n    )\n\n# Save\nchart.render_to_png(f\"plot-{THEME}.png\")\nwith open(f\"plot-{THEME}.html\", \"wb\") as f:\n    f.write(chart.render())\n"}