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