The same plot in 14 other libraries — Python: Altair, Bokeh, lets-plot, Matplotlib, plotnine, Pygal, Seaborn; R: ggplot2; Julia: Makie.jl; JavaScript: Chart.js, D3.js, Apache ECharts, Highcharts, MUI X Charts. Compare all 15 side by side: Swimmer Plot for Clinical Trial Timelines in Python, R, Julia and JavaScript.
A swimmer plot displays individual patient timelines as horizontal bars, commonly used in clinical oncology to visualize treatment duration, response events, and disease progression across a study cohort. Each bar represents one patient, typically sorted by treatment duration, with symbols or color changes marking key clinical events such as partial response, complete response, or progressive disease. This plot is standard in clinical trial publications and regulatory submissions for conveying patient-level longitudinal outcomes at a glance.

""" anyplot.ai
swimmer-clinical-timeline: Swimmer Plot for Clinical Trial Timelines
Library: plotly 7.1.0 | Python 3.14.10
Quality: 86/100 | Updated: 2026-12-04
"""
import os
import numpy as np
import pandas as pd
import plotly.graph_objects as go
# Theme tokens (see prompts/default-style-guide.md)
THEME = os.getenv("ANYPLOT_THEME", "light")
PAGE_BG = "#FAF8F1" if THEME == "light" else "#1A1A17"
ELEVATED_BG = "#FFFDF6" if THEME == "light" else "#242420"
INK = "#1A1A17" if THEME == "light" else "#F0EFE8"
INK_SOFT = "#4A4A44" if THEME == "light" else "#B8B7B0"
INK_MUTED = "#6B6A63" if THEME == "light" else "#A8A79F"
GRID = "rgba(26,26,23,0.15)" if THEME == "light" else "rgba(240,239,232,0.15)"
# Imprint palette — first series always #009E73 (brand green)
IMPRINT_PALETTE = ["#009E73", "#C475FD", "#4467A3", "#BD8233", "#AE3030", "#2ABCCD", "#954477", "#99B314"]
ANYPLOT_AMBER = "#DDCC77" # adverse events / warning
# Constants
EVENT_STYLE = { # clinical meaning decides the colour: red progression, amber adverse event
"partial_response": {"symbol": "triangle-up", "color": IMPRINT_PALETTE[5], "label": "Partial Response"},
"complete_response": {"symbol": "star", "color": IMPRINT_PALETTE[2], "label": "Complete Response"},
"progressive_disease": {"symbol": "diamond", "color": IMPRINT_PALETTE[4], "label": "Progressive Disease"},
"adverse_event": {"symbol": "circle", "color": ANYPLOT_AMBER, "label": "Adverse Event"},
}
ONGOING = "ongoing" # event type of the row that marks a patient still on study at data cutoff
# Columns: set these to your table's column names
PATIENT = "Patient ID" # role: patient_id
DURATION = "Weeks on Study" # role: duration
EVENT_TIME = "Event week" # role: event_time
EVENT_TYPE = "Event type" # role: event_type
ARM = "Treatment arm" # role: group
# Data: replace this block with your own table, for example df = pd.read_csv("trial.csv")
# One row per clinical event of a patient, one row for a patient without events
rng = np.random.default_rng(42)
n_patients = 25
rows = []
for i in range(n_patients):
pid = f"PT-{i + 1:03d}"
arm = "Arm A" if i < 12 else "Arm B"
dur = float(rng.uniform(8, 52) if arm == "Arm A" else rng.uniform(4, 48))
ongoing = rng.random() < 0.3
events = []
if rng.random() < 0.7: # first response, never repeated
kind = "complete_response" if rng.random() < 0.3 else "partial_response"
events.append((kind, dur * rng.uniform(0.2, 0.6)))
for _ in range(rng.integers(0, 3)):
events.append(("adverse_event", dur * rng.uniform(0.05, 0.9)))
if not ongoing and rng.random() < 0.5: # progression ends a patient's follow-up
events.append(("progressive_disease", dur * rng.uniform(0.92, 0.99)))
if ongoing:
events.append((ONGOING, dur))
for kind, t in events or [(None, np.nan)]:
rows.append({PATIENT: pid, ARM: arm, DURATION: dur, EVENT_TIME: t, EVENT_TYPE: kind})
df = pd.DataFrame(rows)
# Plot
patients = df.drop_duplicates(PATIENT).sort_values(DURATION) # ascending: longest ends at the top
order = patients[PATIENT].tolist()
arms = df[ARM].drop_duplicates().tolist()
median_dur = patients[DURATION].median()
fig = go.Figure()
# Duration bars: one trace per treatment arm, which also gives the arm legend entries
for i, arm in enumerate(arms):
sub = patients[patients[ARM] == arm]
fig.add_trace(
go.Bar(
x=sub[DURATION],
y=sub[PATIENT],
orientation="h",
name=arm,
marker={"color": IMPRINT_PALETTE[i], "line": {"width": 0}},
width=0.65,
hovertemplate="%{y}: %{x:.1f} wk<extra></extra>",
)
)
# Clinical event markers: one scatter trace per event type
for kind, style in EVENT_STYLE.items():
ev = df[df[EVENT_TYPE] == kind]
if ev.empty:
continue
fig.add_trace(
go.Scatter(
x=ev[EVENT_TIME],
y=ev[PATIENT],
mode="markers",
name=style["label"],
marker={
"symbol": style["symbol"],
"size": 11,
"color": style["color"],
"line": {"color": INK, "width": 1.0},
},
hovertemplate=f"{style['label']}: %{{x:.1f}} wk<extra></extra>",
)
)
# Ongoing patients: right-pointing arrow just beyond the bar end
ong = df[df[EVENT_TYPE] == ONGOING]
if not ong.empty:
fig.add_trace(
go.Scatter(
x=ong[EVENT_TIME] + df[DURATION].max() * 0.01,
y=ong[PATIENT],
mode="markers",
name="Ongoing",
marker={"symbol": "triangle-right", "size": 12, "color": INK, "line": {"color": INK, "width": 0.5}},
hovertemplate="Still on study<extra></extra>",
)
)
# Median duration reference line
fig.add_vline(
x=median_dur,
line={"color": INK_MUTED, "width": 1.5, "dash": "dot"},
annotation_text=f"Median {median_dur:.1f} wk",
annotation_position="top right",
annotation_font={"size": 9, "color": INK_MUTED},
annotation_bgcolor=ELEVATED_BG,
annotation_bordercolor=INK_MUTED,
annotation_borderwidth=1,
annotation_borderpad=3,
)
# Style
title = "swimmer-clinical-timeline · python · plotly · anyplot.ai"
fig.update_layout(
autosize=False,
paper_bgcolor=PAGE_BG,
plot_bgcolor=PAGE_BG,
barmode="overlay",
title={"text": title, "font": {"size": 16, "color": INK}, "x": 0.5, "xanchor": "center"},
xaxis={
"title": {"text": DURATION, "font": {"size": 12, "color": INK}},
"tickfont": {"size": 10, "color": INK_SOFT},
"gridcolor": GRID,
"linecolor": INK_SOFT,
"zerolinecolor": INK_SOFT,
"showgrid": True,
"showline": True,
"mirror": False,
"range": [0, df[DURATION].max() * 1.1],
},
yaxis={
"title": {"text": PATIENT, "font": {"size": 12, "color": INK}},
"tickfont": {"size": 10, "color": INK_SOFT},
"linecolor": INK_SOFT,
"showgrid": False,
"showline": True,
"mirror": False,
"tickmode": "array",
"tickvals": order,
"categoryorder": "array",
"categoryarray": order,
},
legend={
"bgcolor": ELEVATED_BG,
"bordercolor": INK_SOFT,
"borderwidth": 1,
"font": {"size": 10, "color": INK_SOFT},
"x": 1.02,
"xanchor": "left",
"y": 1.0,
"yanchor": "top",
},
margin={"l": 90, "r": 170, "t": 80, "b": 60},
)
# Save
fig.write_image(f"plot-{THEME}.png", width=800, height=450, scale=4)
fig.write_html(f"plot-{THEME}.html", include_plotlyjs="cdn")
Runnable source as JSON, for any HTTP client: https://api.anyplot.ai/specs/swimmer-clinical-timeline/plotly/code. Any spec id and library id listed in llms-full.txt fit the same URL shape; every URL below is complete and callable.
{
"spec_id": "swimmer-clinical-timeline",
"language": "python",
"library": "plotly",
"page": "https://anyplot.ai/swimmer-clinical-timeline/python/plotly",
"hub": "https://anyplot.ai/swimmer-clinical-timeline",
"code_json": "https://api.anyplot.ai/specs/swimmer-clinical-timeline/plotly/code",
"spec_json": "https://api.anyplot.ai/specs/swimmer-clinical-timeline",
"render_light_png": "https://storage.googleapis.com/anyplot-images/plots/swimmer-clinical-timeline/python/plotly/plot-light.png",
"render_dark_png": "https://storage.googleapis.com/anyplot-images/plots/swimmer-clinical-timeline/python/plotly/plot-dark.png",
"interactive_light_html": "https://storage.googleapis.com/anyplot-images/plots/swimmer-clinical-timeline/python/plotly/plot-light.html",
"interactive_dark_html": "https://storage.googleapis.com/anyplot-images/plots/swimmer-clinical-timeline/python/plotly/plot-dark.html",
"quality_score": 86.0,
"license": "MIT",
"guide": "https://anyplot.ai/llms.txt"
}Part of Swimmer Plot for Clinical Trial Timelines on anyplot.ai.