pypedigree

Generate publication-quality pedigree diagrams from standard genetics pedigree files

v0.10.0

Installation

Without installing: the web app

The web app runs pypedigree in the browser (with Pyodide): paste, drop or open a pedigree file, choose the options, and save an interactive SVG, an SVG for print or a PNG. The file is drawn on your computer and never uploaded. It has every option of a style file, but not the circular layout, PDF output, or separate phenotype and annotation files.

From PyPI

pip install pypedigree

With pandas support

pip install pypedigree[pandas]

From source (development)

git clone https://github.com/bourgeron-lab/pypedigree.git
cd pypedigree
uv sync --extra dev

Requirements

import pypedigree does not import matplotlib: it is loaded on the first PNG/PDF render. Parsing, layout and SVG output (render_interactive_svg, render_svg, --interactive) never load it, so a web server using them avoids its import time and pyplot's global state.

Quick Start

Command Line

# Render a pedigree file to PNG
pypedigree family.ped -o output.png

# Display interactively
pypedigree family.ped --show

# Render specific family at high resolution
pypedigree family.ped --family FAM1 --dpi 300 -o family1.svg

# One file per family: figures/FAM1.svg, figures/FAM2.svg...
pypedigree cohort.ped --output-dir figures/ --format svg

Python Script

from pypedigree import parse_pedigree, render_pedigree

ped = parse_pedigree("family.ped")
fig = render_pedigree(ped, output="output.png")

Programmatic Builder

from pypedigree import PedigreeBuilder

builder = PedigreeBuilder("FAM1")
builder.add_individual("father", sex="male")
builder.add_individual("mother", sex="female")
builder.add_individual("child", sex="male",
                       father="father", mother="mother",
                       phenotype="affected")
fig = builder.render(output="trio.png")
Programmatic API example
Output of the PedigreeBuilder example above

Pedigree File Format

pypedigree reads tab-, comma-, or space-separated pedigree files. The separator is auto-detected. Files are read as UTF-8 on every platform, Windows included; a byte order mark (Excel's “CSV UTF-8”) is ignored, and a file in another encoding is a parse error asking to save it as UTF-8.

Smart Header-Based Column Mapping

When a header row is present, columns are matched by name, not by position. This means you can arrange columns in any order, and any column that doesn't match a known structural name is automatically treated as a phenotype column.

The parser recognises multiple aliases for each structural column:

RoleAccepted Aliases
Family IDFID, family_id, Family
Individual IDID, IID, sample_id, Individual
FatherFather, Pat, Dad, paternal_id
MotherMother, Mat, Mom, Mum, maternal_id
SexSex, Gender
PhenotypePhenotype, Pheno, Affected
Extra columns become phenotypes Any header name that doesn't match one of the structural aliases above is automatically parsed as an extra phenotype column. This makes it easy to add phenotype data without worrying about column positions.

Standard 6-Column Format

ColumnNameDescriptionValues
1family_idFamily identifierAny string
2sample_idIndividual identifier (unique within family)Any string
3paternal_idFather's sample_idID or 0 if unknown
4maternal_idMother's sample_idID or 0 if unknown
5sexBiological sex1=male, 2=female, 0=unknown
6phenotypeAffected status1=unaffected, 2=affected, 0=unknown

A not_sampled column (aliases inferred, unsampled, dummy; 1, yes or true) marks individuals who have a row but were never sampled, such as the “dummy” parents that link real members: they are drawn with a dashed outline like a phantom, but keep their label, parents, phenotypes and their place in a .fam export.

A parent named in the father or mother column but with no row of their own is drawn as a phantom: dashed outline, labelled with that ID, sex from the role, and a PedigreeDataWarning says so. A child with only one parent given gets an unlabelled phantom for the other. Either way the child hangs from both parents, as with PedigreeBuilder; a .fam export leaves phantoms out.

Example: simple_trio.ped

FAM1  father  0       0       1  1
FAM1  mother  0       0       2  1
FAM1  child   father  mother  1  2

Extended Format (Columns 7–10)

ColumnNameDescriptionValues
7date_of_birthBirth dateYYYYMMDD, YYYYMM, or YYYY
8twinsTwin relationshipsTYPE:sibling_id (comma-separated)
9deceasedVital status1=deceased, 0=alive
10probandIndex case1=proband, 0=not
11carrierCarrier status0=not carrier, 1=carrier (heterozygous), 2=obligate carrier. Per-gene status: cr_ columns, see Carrier Notation

Standard notation — pregnancies and pregnancy losses, adoption, childlessness, gamete donors and surrogates, gender identity, the consultand — has its own named columns, see Standard Notation.

Carrier column The carrier column requires a header row to be present. When using inline phenotypes (columns 12+), the carrier column must appear before the phenotype columns.
Twin types MZ = monozygotic (identical), DZ = dizygotic (fraternal), TW = unknown zygosity. Example: MZ:sibling_id

Inline Phenotypes (Columns 11+)

When a header row is present, columns 11 and beyond are parsed as additional phenotype values. Column names from the header define phenotype names.

Example with inline phenotypes

family_id  sample_id  father  mother  sex  pheno  dob  twins  deceased  proband  epilepsy  IQ   SRS
FAM1       father     0       0       1    1      0    0      0         0        0         110  12
FAM1       mother     0       0       2    1      0    0      0         0        1         95   25
FAM1       son        father  mother  1    2      0    0      0         1        1         85   40
FAM1       daughter   father  mother  2    1      0    0      0         0        0         120  8
Phenotype value interpretation
  • Standard pedigree encoding (1/2): values 1=unaffected, 2=affected, 0=unknown and -9=no data are properly handled in extra phenotype columns, following the same convention as the main phenotype column
  • Binary (0 or 1): filled band (1) or empty band (0)
  • Continuous (values > 1): color gradient from white (min) to full color (max), with the value written in the band: “IQ: 90”, or “90” alone, or smaller, as the room allows (a circle's top and bottom bands are narrow; see band_text)
  • PGS column: rendered as a vertical Gaussian distribution curve
  • Missing (., NA, NaN, -9, empty): grey band reading “NA” (the grey of 0=unknown, told apart by the text); a single centred “NA” when every band of the symbol has no data. The text can be turned off with show_na_labels / --no-na-labels
  • Not applicable (N/A, not_applicable, case-insensitive): the phenotype cannot apply to the individual (ovarian cancer for someone assigned male at birth). The band or quadrant stays white, crossed by a thin grey diagonal, and the legend has a “Not applicable” row. It is not data (no part in a gradient’s range); NA keeps meaning no data.
  • a_ prefix columns are annotation columns (text below IDs, not phenotypes)
  • gi_ prefix for gradient inverted (color→white, for metrics where low = bad)
  • cr_ prefix for carrier status of one gene or condition (0/1/2), drawn as a patterned section, see Carrier Notation
  • Comma decimal separator: 0,712 is accepted as 0.712
Binary phenotype rendering Binary phenotypes (including standard 1/2 encoding) are rendered as: color=affected, white=unaffected, grey=unknown. No text labels are shown by default. To display YES/NO text inside the bands, use the show_phenotype_labels style option or the --show-phenotype-labels CLI flag.

Quadrant Layout

By default (since 0.5.0) each symbol is cut in four, one quadrant per phenotype column or cr_ carrier source, up to four. With more, the default "phenotype_layout": "auto" draws horizontal bands instead; --phenotype-layout quadrants does the same with a warning, and --phenotype-layout bands (the default before 0.5.0) always draws one band per column. Carrier sources alone, with no phenotype column, are drawn as with bands. A quadrant shows the same codes as a band; a gradient value is written alone. The legend starts with a key, a square and a circle cut in four with the column names around them. Since the key gives each column's color, the binary columns then share one Affected / Unaffected / Unknown row whose first swatch is striped with their colors ("legend": "compact", the default with quadrants; "full" gives one row per column).

Autism (Autism, ASD, TSA), ADHD (ADHD, TDAH), intellectual disability (ID, DI) and epilepsy columns are recognised by name, whatever their prefix, case or order, and take the top-left, top-right, bottom-left and bottom-right quadrants; other columns take the free quadrants in column order, and phenotype_quadrants places any column, e.g. {"IQ": "bottom-right"}. In both layouts these four phenotypes are drawn in conventional colors by default: autism blue #386eb2, intellectual disability red #d34436, ADHD yellow #e59635, epilepsy purple #5e287e; phenotype_colors overrides them.

pypedigree family.ped --phenotype-layout bands -o family.png   # horizontal bands instead

Separate Phenotype File

Extra phenotypes can also be supplied via a separate TSV file with the --pheno CLI flag:

sample_id  epilepsy  IQ    SRS
father     1         118   45
mother     1         92    78
child      2         105   62

Rows are matched to the pedigree by sample_id. Sample IDs that match no individual are listed in a warning (PedigreeDataWarning, Warning: … on the CLI) and their values are ignored; an individual with no row is drawn with “NA” bands.

CLI Reference

pypedigree PEDIGREE_FILE [OPTIONS]
OptionDescriptionDefault
-o, --output PATHOutput file path (format from extension: .png, .svg, .pdf)None (display)
--format FORMATForce output format: png, svg, pdfAuto-detect
--family IDRender only this familyAll families
--output-dir DIROne file per family in DIR, named after the family ID (FAM1.png; .svg with --interactive), with the colors and legend of the whole file. IDs are made safe for file names; two IDs giving the same name get _2, _3… A family that fails is reported, the others are written, and the exit code is 1. Not with -o or --show—
--dpi INTOutput resolution in DPI150
--showDisplay interactively (matplotlib window)Off
--style PATHJSON file with PedigreeStyle overridesNone
--separator SEPForce separator: tab, comma, spaceAuto-detect
--pheno PATHSeparate .pheno TSV file for extra phenotypesNone
--annotations PATHSeparate TSV file with annotation text (displayed below individual IDs)None
--outline-color COLORShape outline color (e.g. grey, #888)black
--carrier-notation [nsgc2022|legacy]Carrier notation: patterned sections (NSGC 2022) or half-fill and center dotnsgc2022
--min-font-size PTSmallest size of any text, in points (style min_font_size; e.g. 6 for journals)None
--no-labelsHide sample ID labels under shapesOff
--no-legendHide phenotype legendOff
--show-phenotype-labelsShow YES/NO text inside binary phenotype bands (hidden by default)Off
--phenotype-layoutauto (quadrants up to four phenotypes, bands beyond), quadrants (the symbol cut in four, one quadrant per phenotype, up to four) or bands (horizontal bands)auto
--pgs-scalePGS position: zscore, minmax over the pedigree (raw scores) or percentile (fixed scales mark ±2 SD); a warning when a PGS column drawn as z-scores does not look like themzscore
--show-pgs-valuesWrite each PGS value beside its marker (style show_pgs_values)Off
--no-na-labelsDo not write “NA” in bands with no data (they stay grey, like unknown)Off
--plinkTreat input as PLINK .ped file (ignore genotype columns after column 6)Off
--interactiveGenerate interactive SVG with tooltips, click highlighting, and zoom/pan (same bands, legend and PGS curves as the PNG; not with --circular)Off
--no-scriptWith --interactive: the same SVG without script or tooltip, for print or for a page that adds its own behaviour (render_svg())Off
--id-prefix PREFIXWith --interactive: prepend PREFIX to every id in the SVG, so several figures can share one page—
--responsiveWith --interactive: width="100%" and no height, so the figure fills its container's widthOff
--circularUse circular/radial layout with founders at centre, descendants on concentric ringsOff
--versionShow version and exit—

Examples

# Basic rendering
pypedigree family.ped -o pedigree.png

# SVG with custom DPI and no labels
pypedigree family.ped -o pedigree.svg --dpi 300 --no-labels

# With external phenotype file and custom style
pypedigree family.ped --pheno phenotypes.tsv --style custom.json -o result.pdf

# Grey outlines for a cleaner look
pypedigree family.ped --outline-color grey -o pedigree.png

# Interactive SVG with tooltips and click highlighting
pypedigree family.ped --interactive -o pedigree.svg

# Show YES/NO labels in binary phenotype bands
pypedigree family.ped --show-phenotype-labels -o pedigree.png

# Read a PLINK .fam file (auto-detected from extension)
pypedigree family.fam -o pedigree.png

# Read a PLINK .ped file (use --plink to ignore genotype columns)
pypedigree family.ped --plink -o pedigree.png

Python API

Parsing

parse_pedigree(file_path)

Parse a pedigree file (.ped) into a Pedigree object.

from pypedigree import parse_pedigree

ped = parse_pedigree("family.ped")
for fam_id, family in ped.families.items():
    print(f"{fam_id}: {len(family.individuals)} individuals")

parse_pedigree_from_string(text)

Parse pedigree data from a string (useful for testing or embedded data).

from pypedigree import parse_pedigree_from_string

data = """FAM1\tfather\t0\t0\t1\t1
FAM1\tmother\t0\t0\t2\t1
FAM1\tchild\tfather\tmother\t1\t2"""
ped = parse_pedigree_from_string(data)

parse_pedigree_from_dataframe(df)

Parse from a pandas DataFrame. Requires pip install pypedigree[pandas]. The DataFrame is read as a pedigree file would be. When its first column is named like a family ID column (FID, family_id, family) or another known header name, the column names are the header: columns are matched by name, and phenotype, PGS, annotation and notation columns are drawn. Columns named 0, 1, 2... (header=None) are read by position, the first ten only. NaN is a missing value, never 0.

import pandas as pd
from pypedigree import parse_pedigree_from_dataframe

# a file with a header: FID, IID, PAT, MAT, SEX, PHENO, b_autism, PGS_autism...
df = pd.read_csv("family.ped", sep="\t")
ped = parse_pedigree_from_dataframe(df)

# no header: columns by position
df = pd.read_csv("family.fam", sep="\t", header=None)
ped = parse_pedigree_from_dataframe(df)

parse_phenotype_file(file_path)

Parse a separate phenotype TSV file.

from pypedigree import parse_phenotype_file, apply_phenotypes_to_pedigree

pheno_data, pheno_names = parse_phenotype_file("phenotypes.tsv")
apply_phenotypes_to_pedigree(ped, pheno_data, pheno_names)

parse_annotation_file(file_path)

Parse an external annotation TSV file. First row is a header (sample_id, ann1, ann2, ...), subsequent rows contain text values.

from pypedigree import parse_annotation_file, apply_annotations_to_pedigree

ann_data, ann_names = parse_annotation_file("annotations.tsv")
apply_annotations_to_pedigree(ped, ann_data, ann_names)

Rendering

render_pedigree(pedigree, ...)

Render all families in a pedigree. Returns a matplotlib Figure.

pedigree: Pedigree
The pedigree to render.
style: PedigreeStyle | None = None
Visual style (defaults if None).
output: str | Path | None = None
Save to file (PNG/SVG/PDF). None for in-memory only.
ax: matplotlib.axes.Axes | None = None
Render onto existing axes.
show_labels: bool = True
Show sample ID labels under shapes.
show_legend: bool = True
Show phenotype legend (when phenotypes + colors exist).
circular: bool = False
Use circular/radial layout (founders at centre, descendants on concentric rings).
from pypedigree import parse_pedigree, render_pedigree, PedigreeStyle

ped = parse_pedigree("family.ped")
style = PedigreeStyle(dpi=300)
fig = render_pedigree(ped, style=style, output="high_res.png")

render_family(family, ...)

Render a single Family object. Returns (Figure, FamilyLayout).

from pypedigree import parse_pedigree, render_family

ped = parse_pedigree("family.ped")
family = list(ped.families.values())[0]
fig, layout = render_family(family)
fig.savefig("family.png", dpi=150, bbox_inches="tight")

render_interactive_svg(pedigree, ...)

Render all families as an interactive SVG with tooltips, click highlighting, and zoom/pan. Returns the SVG markup as a string. Draws the same figure as render_pedigree(). No additional dependencies required.

pedigree: Pedigree
The pedigree to render.
style: PedigreeStyle | None = None
Visual style (defaults if None).
output: str | Path | None = None
Save SVG to file. None for in-memory only.
show_labels: bool = True
Draw sample ID labels under shapes.
show_legend: bool = True
Draw the phenotype and carrier legend.
id_prefix: str = ""
Prepended to every id in the SVG (and to the url(#…) and href="#…" references), so several figures can share a page. Letters, digits, _, -, ., starting with a letter or _; otherwise ValueError.
responsive: bool = False
Write width="100%" and no height, keeping the viewBox: the figure fills its container's width.
from pypedigree import parse_pedigree, render_interactive_svg

ped = parse_pedigree("family.ped")
svg_str = render_interactive_svg(ped, output="interactive.svg")

render_svg(pedigree, ...)

The same drawing without script and without the tooltip group, for a printed report or for a page that adds its own behaviour. Each individual keeps its <title> and its data-* attributes. Same arguments as render_interactive_svg().

render_families(pedigree, output_dir, ...)

Draw each family into its own file in output_dir (created if needed) and return a dict of family ID → Path. Every family has the colors, column modes and legend of the whole pedigree, so the figures of a cohort can be compared. The CLI's --output-dir. File names come from family_file_names(ids): other characters than letters, digits, -, _ and . become _, Windows device names get a _, and two IDs giving the same name (ignoring case) get _2, _3… with a warning.

fmt: str = "png"
"png", "pdf" or "svg" (matplotlib's SVG). Ignored with interactive.
family_ids: Iterable[str] | None = None
Families to draw, in order (default: all). KeyError for an unknown ID.
style, show_labels, show_legend, circular
As in render_pedigree(). The style is checked once, before anything is drawn.
interactive: bool = False
Write render_interactive_svg()'s SVG (matplotlib is not imported); with script=False, render_svg()'s. id_prefix and responsive as there.

A family that fails does not stop the others: once all are drawn, PedigreeBatchError is raised, with .written and .failures (family ID → message). Figures are closed as they are saved.

from pypedigree import parse_pedigree, render_families

ped = parse_pedigree("cohort.ped")
files = render_families(ped, "figures", fmt="svg")

Layout (advanced)

compute_layout(family, style, *, labels=True)

Compute layout coordinates without rendering. Returns a FamilyLayout with node positions and edge geometry. With labels=True (what the renderers pass when labels are shown), neighbours whose labels would overlap are moved apart by the room the labels need: long IDs, a large font_size or long annotations no longer run into each other.

from pypedigree import compute_layout, PedigreeStyle

layout = compute_layout(family, PedigreeStyle())
for node in layout.nodes:
    print(f"{node.individual_id}: x={node.x:.1f}, y={node.y:.1f}")

compute_layout_circular(family, style)

Compute circular/radial layout coordinates. Founders sit at the centre and each later generation on its own concentric ring, in the left-to-right order of the hierarchical layout wrapped around the circle. The circular layout therefore inherits its guarantees: siblings stay together, sibship arcs of different couples never overlap, partners sit side by side, and tangled loops are drawn with duplicated individuals.

from pypedigree import compute_layout_circular, PedigreeStyle

layout = compute_layout_circular(family, PedigreeStyle())
for node in layout.nodes:
    print(f"{node.individual_id}: x={node.x:.1f}, y={node.y:.1f}")

base_radius is expanded automatically when a ring would be too crowded for the shapes to fit, so nodes never overlap. Shapes stay upright: a square turned to face outward would read as the unknown-sex diamond, and phenotype bands stay horizontal as in the hierarchical layout. ID labels are set outside each shape, away from the lines arriving from the centre, on a white backing: radially outward, or, where a line, a shape or another label is in the way, turned aside to the first free direction. The labels are placed when the figure is drawn, at its final size, so they also stay clear when the figure is resized after rendering. Twins hang from one point of the sibship arc, as a V with a bar for MZ twins, and duplicates are joined to their original by a dotted arc.

PedigreeBuilder API

The PedigreeBuilder provides a fluent interface for constructing pedigrees programmatically, without writing .ped files. All methods return self for method chaining.

PedigreeBuilder(family_id="FAM1")

Create a new builder with a default family ID.

add_individual(sample_id, ...)

Add an individual to the pedigree.

sample_id: str
Unique identifier for this individual (required).
sex: str | Sex = "unknown"
Biological sex: "male", "female", "unknown" (or "m", "f", "u", "1", "2", "0").
phenotype: str | Phenotype = "unknown"
Affected status: "affected", "unaffected", "unknown".
father: str | None = None
Father's sample_id. Phantom parent created if not added explicitly.
mother: str | None = None
Mother's sample_id. Phantom parent created if not added explicitly.
family_id: str | None = None
Override the builder's default family ID.
deceased: bool = False
Whether this individual is deceased (diagonal line through shape).
proband: bool = False
Whether this is the proband/index case (arrow marker).
inferred: bool = False
Never sampled or sequenced, only links real members (“dummy”): dashed outline like a phantom, with label, parents and phenotypes kept.
date_of_birth: str | None = None
Date of birth string.
phenotypes: dict[str, float | int] | None = None
Extra phenotype values as {name: value}.
carrier: bool = False
Whether this individual is a carrier (heterozygous). Rendered as a patterned section (NSGC 2022), or a half-filled shape with the legacy notation.
obligate_carrier: bool = False
Whether this is an obligate carrier. Rendered as a sparser pattern (NSGC 2022), or a center dot with the legacy notation.
annotations: list[str] | None = None
Text lines to display below the individual's ID label (e.g. variant names).
pregnancy: str | Pregnancy | None = None
"P", "SAB", "TOP", "ECT" or "SB", see Standard Notation.
adopted: str | Adoption | None = None
"in" (father/mother are the adoptive parents) or "out".
childless: str | Childlessness | None = None
"choice" or "infertility".
art: str | ReproductiveRole | None = None
"D" gamete donor or "S" surrogate.
gender: str | Gender | None = None
Gender identity, "man", "woman" or "nonbinary": the symbol follows it, and sex is the sex assigned at birth.
consultand: bool = False
Arrow without “P”.
evaluated: bool | str = False
Documented evaluation: True draws an asterisk at the lower right; text is the result, written below.
twin_of: str | list[str] | None = None
Sample ID of this individual's twin (a list for triplets and more), added before or after.
css_class: str | list[str] | None = None
Extra classes on the individual's node in the interactive SVG.
data: Mapping[str, object] | None = None
Extra data-* attributes on that node, e.g. {"qc": "high"} → data-qc="high".
twin_type: str | TwinType = "TW"
"MZ" monozygotic, "DZ" dizygotic or "TW" zygosity unknown.

add_twins(sample_ids, twin_type="TW")

Declare a group of twins (or triplets) of one zygosity, as the twins column does: every member is recorded as the twin of every other, and the individuals may be added before or after. A twin never added, twins in different families or not sharing their parents give a PedigreeDataWarning at build().

builder.add_twins(["S7", "S8"], "MZ")

add_union(partner1, partner2, ...)

Explicitly add a union between two individuals. Unions are auto-inferred from parent references, so this is only needed for childless couples or to set consanguinity/broken flags.

partner1: str
First partner's sample_id.
partner2: str
Second partner's sample_id.
consanguineous: bool = False
Double-line relationship (shared ancestors).
broken: bool = False
Broken-line relationship (dissolved).

set_style(style)

Set a custom PedigreeStyle for rendering.

build() → Pedigree

Build a Pedigree object from added individuals. Auto-infers unions and creates phantom parents, as the parser does: a parent named but not added becomes a phantom with that ID, and a child with only one parent gets an unlabelled phantom for the other.

render(output=None, ...) → Figure

Build and render in one step. Auto-assigns phenotype colors if not set.

render_interactive_svg(output=None) → str

Build and render as an interactive SVG. Returns the SVG markup as a string. If output is provided, the SVG is also written to that file path. See the Interactive SVG section for details.

render_svg(output=None) → str

Build and render as a static SVG (no script, no tooltip). Both take id_prefix= and responsive=.

Complete Example

from pypedigree import PedigreeBuilder

builder = PedigreeBuilder("FAM1")

# Generation 1: founders
builder.add_individual("gf", sex="male")
builder.add_individual("gm", sex="female")

# Generation 2
builder.add_individual("father", sex="male", father="gf", mother="gm")
builder.add_individual("mother", sex="female")

# Generation 3 with phenotypes
builder.add_individual("child1", sex="male",
    father="father", mother="mother",
    phenotype="affected", proband=True,
    phenotypes={"IQ": 85, "epilepsy": 1})
builder.add_individual("child2", sex="female",
    father="father", mother="mother",
    phenotypes={"IQ": 120, "epilepsy": 0})

fig = builder.render(output="family.png")

Jupyter Notebook Integration

The builder has built-in Jupyter support via _repr_png_. Simply evaluate a builder cell to see the pedigree inline:

builder  # Displays the pedigree diagram inline

Multi-Phenotype Support

pypedigree can display multiple phenotypes per individual, each in a quadrant of the symbol (the default, up to four) or in a horizontal band, as a color or a gradient fill.

Phenotype Types

TypeValuesRendering
Binary0 or 1Empty (0) or filled (1) color band
ContinuousNumeric > 1Color gradient: white (min) → full color (max)
PGSAny numericVertical Gaussian distribution curve (to the left of shape)
Missing., NA, NaN, -9, emptyGrey band reading “NA”
Multi-phenotype rendering
Multi-phenotype pedigree with epilepsy (binary), IQ (continuous), and SRS (continuous)

Setting Phenotype Colors

Via CLI (JSON style file)

// style.json
{
  "phenotype_colors": {
    "epilepsy": "#e74c3c",
    "IQ": "#3498db",
    "SRS": "#e67e22"
  }
}
pypedigree family.ped --style style.json -o output.png

Via Python

style = PedigreeStyle()
style.phenotype_colors = {
    "epilepsy": "#e74c3c",
    "IQ": "#3498db",
    "SRS": "#e67e22",
}
fig = render_pedigree(ped, style=style)

Auto-assigned

Columns without a color in phenotype_colors get one from the default palette, by their position among the columns, also when other columns have one. A color that repeats one already in the figure (a known phenotype's, or one you chose), or looks like it, is replaced by the next distinct one, from the palette then brown, light magenta and olive: two outlines or bands never look alike. This happens for every entry point — the CLI, render_pedigree() and PedigreeBuilder — via resolve_style(), so all three produce the same figure for the same input.

PGS (Polygenic Score) Display

When a column is named PGS (case-insensitive), it is rendered as a vertical Gaussian curve to the left of each individual's shape, instead of a band. The curve's position along the x-axis reflects the PGS value relative to other individuals.

PGS rendering
Pedigree with phenotypes in quadrants and PGS Gaussian curves

PGS on a Fixed Scale

By default a PGS value is placed between the pedigree's lowest and highest score, so in a trio with z = +2.5, −0.2 and +1.1 the parent at the 42nd percentile sits at the bottom of the curve. With --pgs-scale zscore (style "pgs_scale": "zscore") each value is a z-score placed on the drawn standard normal, the same for every pedigree; with --pgs-scale percentile it is a population percentile (0–100). On these fixed scales the ±2 SD tails are marked with dotted lines, the legend names the scale, and the SVG tooltip gives z and percentile (z = +1.10, 86th percentile). PGS curves are drawn even when the pedigree has no other phenotype column.

The legend's PGS row writes each score's name after a dash of its color (“PGS distribution: –– autism –– ADHD”), so the markers can be told apart; phenotype_labels renames them ({"PGS_EA": "educational attainment"}).

A printed figure shows where a score sits on the curve, not its value. --show-pgs-values (style "show_pgs_values": true) writes each value beside its marker, in the marker's color, on the far side of the curve from the symbol: “+2.1” or “−0.4” on the z scale, the rounded percentile, or the value to three significant digits; close values are spread apart, and the symbols move apart to make room. Markers of different scores with close values have their dots set side by side, so none hides another.

Multiple PGS Columns

Any column starting with PGS (case-insensitive) is treated as a PGS column. For example: PGS_autism, PGS_IQ, PGS_ADHD. All PGS columns share a single gaussian curve, with each trait's individual score marked by a colored dashed line. Colors are set via the pgs_colors style option. Without it, a single PGS column is red (#e74c3c) and several get distinct colors: a score named after a known phenotype (PGS_autism, PGS_ADHD, PGS_ID, PGS_epilepsy) takes that phenotype's color, the one its column has in the figure if there is one; the others take the first color unlike the other scores and the phenotype bands.

pTDT Deviations

A column whose name starts with pTDT (case-insensitive, e.g. pTDT_autism) holds each child’s polygenic transmission deviation, (PGSchild − PGSmid-parent) / SD(PGSmid-parent) (Weiner et al. 2017). It is drawn with the PGS curve, always on the z scale, captioned “pTDT”; the legend has its own row and the tooltip reads “pTDT = +2.12”. An individual’s curve shows its pTDT deviations if it has any, otherwise its PGS, so the parents’ PGS and the children’s pTDT share a figure. pypedigree does not compute the deviations: give them in the file.

Custom Gradient Ranges

By default, gradient values are normalized to [0,1] using the data's min/max. You can override this with the gradient_range style option to define fixed scales:

{
    "gradient_range": {
        "SRS": [40, 90]
    }
}

Diverging (Tricolor) Gradient

For phenotypes with a meaningful midpoint (e.g., IQ where 100 is average), use gradient_diverging to create a red→white→green scale:

{
    "gradient_diverging": {
        "IQ": {"min": 40, "mid": 100, "max": 160, "color_low": "#e74c3c", "color_high": "#2ecc71"}
    }
}

Values below the midpoint blend toward color_low, values above blend toward color_high, and the midpoint is white.

Categorical Columns

Each distinct value of a c_ column gets its own color, assigned in the order the values appear in the file so the result is reproducible. The column's own phenotype_colors entry is used for the first value; the remaining values avoid both that color and the colors of the other phenotype columns, so two bands on the same individual stay visually distinct. The legend lists exactly the values present in the rendered pedigree.

Default Color Palette

When colors are auto-assigned, the following 8-color palette is used, then three extra colors when it runs short (brown #8c564b, light magenta #e377c2, olive #bcbd22):

#e74c3c #3498db #e67e22 #2ecc71 #9b59b6 #1abc9c #f1c40f #e91e63

Phenotype Display Modes

By default, pypedigree auto-detects how to render each phenotype column (binary vs. continuous). You can override this behaviour by adding a prefix to the column name in the header row. The prefix is stripped from the display name in legends and labels.

Prefix Reference

PrefixModeRenderingUse Case
b_ Binary Color band when affected, white when unaffected, grey when unknown. No text by default. Diagnoses, yes/no traits
g_ Gradient White→color continuous gradient scale. Value labels shown inside band. Quantitative scores (IQ, SRS, etc.)
o_ Outline Colored shape border when affected, instead of a filled band. Does not consume band space. An individual affected in several o_ columns gets one border per column, inner first, in column order. Proband marker, secondary highlight
c_ Categorical Distinct color per unique string value, shown as a colored band with label. Diagnosis categories, subtypes
cr_ Carrier Carrier status of one gene or condition: 0 not a carrier, 1 carrier, 2 obligate carrier. Drawn as a patterned section of the symbol, with its own legend row. CFTR, HEXA, ATM carrier status
gi_GRADIENT_INVERTED Color→white gradient (inverted). High value = white, low value = full color. Use for metrics where low = bad (e.g., IQ: low IQ = red). Any numeric Color gradient bar (reversed direction)
a_Annotation Text annotation displayed below the individual's ID label. Not rendered as a phenotype band. Any text string Italic grey text below ID
(none) Auto Resolved once per column from all of its values: categorical if any value is a string, gradient if any numeric value falls outside 0/1/2, binary otherwise. A column therefore never mixes band types, and its legend row always matches its bands. Backward-compatible default

Example Header with Prefixes

FID  ID  Father  Mother  Sex  b_ASD  g_IQ  o_Proband  c_Diagnosis

This defines four phenotype columns:

Prefix is stripped from display name The prefix (b_, g_, o_, c_) is removed from the phenotype name shown in legends and labels. For example, b_ASD appears as "ASD" in the legend.

Complete Example File

FID   ID        Father  Mother  Sex  b_ASD  g_IQ  o_Proband  c_Diagnosis
FAM1  father    0       0       1    0      105   0          Control
FAM1  mother    0       0       2    0      98    0          Control
FAM1  child1    father  mother  1    2      72    1          ASD
FAM1  child2    father  mother  2    1      110   0          Control

Python API

The PhenotypeDisplayMode enum is exported from pypedigree and represents the five display modes:

from pypedigree import PhenotypeDisplayMode

# Available modes:
PhenotypeDisplayMode.AUTO         # No prefix, auto-detect
PhenotypeDisplayMode.BINARY       # b_ prefix
PhenotypeDisplayMode.GRADIENT     # g_ prefix
PhenotypeDisplayMode.OUTLINE      # o_ prefix
PhenotypeDisplayMode.CATEGORICAL  # c_ prefix
Combining with smart header mapping Prefixed column names work seamlessly with the smart header-based column mapping. Any column whose name (after alias matching) is not a known structural column is treated as a phenotype, and the prefix determines its display mode.

Annotations

Annotations are text lines displayed below each individual's ID label. They are useful for showing variant names, gene names, or other per-individual notes.

Inline Annotations (a_ prefix)

Add columns with the a_ prefix in the .ped header. The prefix is stripped for display; only the value is shown.

FID   IID     PAT     MAT     SEX  b_Autism  IQ   g_SRS  a_Gene1  a_Gene2
FAM1  father  0       0       1    1         112  48     CHD8
FAM1  mother  0       0       2    1         -9   -9              ARID1B
FAM1  child   father  mother  1    2         81   83     CHD8     ARID1B

Missing values (0, -9, NA, empty) produce no annotation line. When annotations are present, the vertical spacing between generations is automatically increased to prevent overlap.

External Annotation File

Annotations can also be loaded from a separate TSV file via --annotations PATH:

IID     Gene1  Gene2
father  CHD8
mother         ARID1B
child   CHD8   ARID1B

Python API

from pypedigree import PedigreeBuilder

builder = PedigreeBuilder("FAM1")
builder.add_individual("father", sex="male",
                       annotations=["CHD8"])
builder.add_individual("child", sex="male",
                       annotations=["CHD8", "ARID1B"])

Carrier Notation

pypedigree follows the NSGC focused revision of the standardized pedigree nomenclature (Bennett et al., J Genet Couns 2022;31(6):1238–48), which no longer marks carriers with a dot: the symbol is divided into as many sections as needed, and each carrier result gets its own fill pattern, defined in the legend. An affected carrier, or the carrier of two conditions, therefore shows every result.

Visual Representations

StatusSymbol (default, NSGC 2022)Symbol (carrier_notation: "legacy")
CarrierPatterned section, one pattern per carrier sourceHalf-filled shape
Obligate carrierThe same pattern at half the densityCenter dot
Affected carrierSymbol split in two: filled section, then patterned sectionHalf-filled shape (the affected fill is not shown)

Sections are vertical and ordered left to right: the affected section first, then one per carrier source in column order. A carrier of a single result has a fully patterned symbol. When phenotype bands are drawn, each carrier source is an extra band below them, at the same place for everyone.

Carrier columns for two genes
carrier_genes.ped: one cr_ column per gene. The father carries both CFTR and HEXA; child1 is affected and an obligate CFTR carrier.

File Format

Carrier status comes from the carrier column and from any number of cr_ columns (one per gene or condition, e.g. cr_CFTR). Each is a separate carrier source, with its own pattern and legend row, and accepts:

ValueMeaning
0Not a carrier
1Carrier (heterozygous)
2Obligate carrier, as declared in the file (pypedigree does not infer it)
-9, NA, emptyUnknown (cr_ columns only): no section, or a grey “NA” band

Example with carrier columns

family_id  sample_id  father  mother  sex  pheno  cr_CFTR  cr_HEXA
FAM1       father     0       0       1    1      1        1
FAM1       mother     0       0       2    2      0        0
FAM1       son        father  mother  1    2      2        0
FAM1       daughter   father  mother  2    1      0        -9

Programmatic API (PedigreeBuilder)

Use the carrier and obligate_carrier parameters of add_individual() for the carrier column, and cr_-prefixed keys in phenotypes for per-gene status:

from pypedigree import PedigreeBuilder

builder = PedigreeBuilder("FAM1")
builder.add_individual("father", sex="male", carrier=True)
builder.add_individual("mother", sex="female", phenotypes={"cr_CFTR": 1})
builder.add_individual("child", sex="female",
    father="father", mother="mother",
    obligate_carrier=True)
fig = builder.render(output="carriers.png")

Legacy notation

The pre-2022 notation stays available for the carrier column: PedigreeStyle(carrier_notation="legacy"), "carrier_notation": "legacy" in a style file, or --carrier-notation legacy on the command line. cr_ columns are still drawn as patterned sections. The radius of the legacy center dot is set by carrier_dot_radius (default 0.08).

Standard Notation

Beyond sex, affection status, death, twins and carriers, pypedigree draws the other symbols of the NSGC nomenclature (Bennett et al., J Genet Couns 2008;17:424–33, and its 2022 revision centred on sex and gender) in the PNG and the interactive SVG, in both layouts. Each comes from one column, recognised by name in the header row.

Standard notation symbols
nomenclature.ped (family FAM1): infertility and childlessness by choice (II-1, II-5), the consultand (II-2), a transgender woman and a non-binary person (II-4, II-5), a miscarriage (II-6); children adopted in and out (III-2, III-3), a stillbirth, an affected termination, an ectopic pregnancy and an ongoing pregnancy (III-4 to III-7).

Columns and codes

Column names and codes are case-insensitive (aliases in brackets). 0, -9, NA, . or an empty cell mean nothing to note; any other value is an error naming the line.

ColumnCodesDrawn as
pregnancy (pregnancy_outcome, outcome)P ongoing, SAB miscarriage, TOP termination, ECT ectopic, SB stillbirthP: “P” inside the symbol. SAB, TOP, ECT: a triangle, filled when affected, struck through for a termination, “ECT” below. SB: the symbol struck through, “SB” below
adopted (adoption)in / 1 (parents given are adoptive), out / 2 (they are biological)Brackets around the symbol; the line to adoptive parents is dashed
childless (childlessness, infertility)choice / 1, infertility / 2A line below the symbol ending in one bar (no children by choice or reason unknown), or two (infertility); choice:<ID> or infertility:<ID> for a couple without children, the marker hanging from the middle of their relationship line
art (assisted_reproduction)D gamete donor, S surrogate (GC accepted)“D” or “S” inside the symbol
gender_identity (identity)man, woman, nonbinary (also M/F/NB, 1/2/3)The symbol follows the gender identity (square, circle, diamond); sex becomes the sex assigned at birth, written below as AMAB or AFAB when the two differ
consultand1An arrow without “P”
count (number)2 or more, or nSeveral individuals in one symbol: the number written inside (cannot be a parent)
asymptomatic (presymptomatic)1Asymptomatic or presymptomatic carrier: a vertical line through the symbol, past its top and bottom, with a legend row; with phenotype_layout “auto” the figure is drawn with bands, not quadrants
evaluated1, or a result (WGS: negative)Documented evaluation, records reviewed: an asterisk at the lower right of the symbol (Bennett et al. 2022, Fig. 2); a result is written below, without the “E” the 2022 revision dropped
The gender column A column named gender is the sex column, as before, unless the header also has a sex column: then it is the gender identity.

Gestational age, karyotype or the reason for infertility go in a_ annotation columns. Notes (“SB”, “ECT”, “AMAB”) are written under the ID label, before annotations. A pregnancy-loss triangle has no room for phenotype bands: in a figure with bands it takes the color of the individual's first band. The letter “P”, “D” or “S” stays at the centre of the symbol, on a white patch over bands or quadrants; a band’s text that would run into it moves to its right. The documented-evaluation asterisk keeps a gap of 0.3 of its size from the outline, whatever the scale.

Programmatic API

builder.add_individual("c1", father="f", mother="m", pregnancy="SAB", annotations=["8 wk"])
builder.add_individual("c2", sex="male", father="f", mother="m", gender="woman", adopted="in")

build_notation() turns the same codes into a Notation, the frozen dataclass attached to every Individual and NodeLayout.

Not covered

The diagonal lines that join a gamete donor or a surrogate to a pregnancy in the NSGC figures: in a pedigree file a donor is a parent and is joined to the other parent like any couple. Several individuals in one symbol (“n”), the asymptomatic-carrier vertical line, and childlessness of a couple (the marker hangs from one individual).

Interactive SVG Export

pypedigree can generate interactive SVG files with built-in tooltips, click-to-highlight, and zoom/pan capabilities. Interactive SVGs are self-contained HTML/SVG files that work in any modern browser with no additional dependencies.

Features

Same figure as the PNG

The interactive SVG draws everything the PNG/PDF output draws: phenotype bands (binary, gradient, diverging, categorical), o_ outline colors, PGS distribution curves, a_ annotations, carrier notation and the legend (hidden with --no-legend). Both renderers take their decisions from the same code (pypedigree.phenotypes and pypedigree.carriers), so the two outputs always agree. Several families are drawn side by side, each with its title.

For a page that embeds the SVG, each individual is a <g class="node"> with data-id, data-parents, data-children, data-siblings, and data-x, data-y (the centre of the symbol) and data-size (its size), in the coordinates of #main-group: an element appended inside that group at those coordinates stays on the node through zoom and pan, so a host can draw overlays (observed relatedness, links the pedigree does not show).

Each individual's tooltip also lists every value, for example ID: 1 | Sex: Male | Phenotype: Affected | IQ: 90 | Dx: ASD. The circular layout (--circular) is not available in interactive mode.

Inlining in a page

The SVG can be put in an HTML page (as innerHTML or in a template) or in an HTML report that is printed, next to other SVGs. Its root has the class pypedigree, its CSS only applies under that class, and its script only acts on its own figure (document.currentScript.closest('svg')), with no listener on the window.

from pypedigree import render_interactive_svg, render_svg

on_page = render_interactive_svg(ped, id_prefix="fam-a-", responsive=True)
in_report = render_svg(ped, id_prefix="report-fam-a-", responsive=True)

CLI Usage

Use the --interactive flag to generate an interactive SVG instead of a static image:

pypedigree family.ped --interactive -o pedigree.svg

# For a web page or a printed report: no script, unique ids, fluid width
pypedigree family.ped --interactive --no-script --id-prefix fam1- --responsive -o pedigree.svg
Output format The --interactive flag automatically produces SVG output. If the output path has a different extension, it will be overridden to .svg.

Python API

render_interactive_svg(pedigree, ...)

Render all families in a pedigree as an interactive SVG. Returns the SVG markup as a string.

from pypedigree import parse_pedigree, render_interactive_svg

ped = parse_pedigree("family.ped")
svg_str = render_interactive_svg(ped, output="interactive.svg")

PedigreeBuilder.render_interactive_svg(output=None, *, style=None, show_labels=True, show_legend=True, id_prefix="", responsive=False)

Build and render as an interactive SVG from the builder API:

from pypedigree import PedigreeBuilder

builder = PedigreeBuilder("FAM1")
builder.add_individual("father", sex="male")
builder.add_individual("mother", sex="female")
builder.add_individual("child", sex="male",
    father="father", mother="mother",
    phenotype="affected")
svg_str = builder.render_interactive_svg(output="interactive.svg")

Styling & Configuration

All visual parameters are controlled through the PedigreeStyle dataclass. Styles can be set in Python or loaded from a JSON file via --style.

PedigreeStyle Parameters

ParameterTypeDefaultDescription
shape_sizefloat0.8Individual shape side length
shape_line_widthfloat1.5Shape outline width
fill_colorstr"black"Affected individual fill color
outline_colorstr"black"Shape and marker outline color
phantom_line_stylestr"--"Line style for phantom parents
line_colorstr"black"Connection line color
line_widthfloat1.0Connection line width
double_line_gapfloat0.06Gap between consanguinity double lines
broken_gap_sizefloat0.15Gap size in broken relationship lines
font_sizefloat8.0Label and text font size, in points. The legend panel is sized from it (text, swatches and row height), so raise it to keep a figure legible once scaled down for print
min_font_sizefloat | NoneNoneSmallest size of any text, in points (e.g. 6, a common journal rule). Notes, annotations, band and quadrant text, “NA”, “PGS” captions and the legend, drawn at fractions of font_size, are raised to it; the layout and the legend make room. PedigreeStyle.text_size(scale) gives the size of any text
font_familystr"sans-serif"Font family for all text
label_offsetfloat0.15Distance below shape for label
generation_gapfloat2.0Vertical spacing between generations
sibling_gapfloat1.5Horizontal spacing between siblings (more where long labels need it)
couple_gapfloat1.5Horizontal spacing between partners (more where long labels need it)
min_node_distancefloat1.2Deprecated, no effect: sibling_gap and couple_gap set the spacing. To be removed in 1.0
phenotype_colorsdict{}Phenotype name → hex color mapping
dpiint150Output resolution
fig_widthfloat10.0Width a small pedigree is drawn to fill (inches); the figure is then fitted to the drawing
fig_heightfloat8.0Height a small pedigree is drawn to fill (inches); the figure is then fitted to the drawing
marginfloat0.5Figure margin (inches)
carrier_notationstr"nsgc2022""nsgc2022": patterned sections, one per carrier result (Bennett et al. 2022). "legacy": half-filled shape and center dot
carrier_dot_radiusfloat0.08Radius of the center dot for obligate carriers (legacy notation)
show_phenotype_labelsboolFalseShow YES/NO text inside binary phenotype bands
phenotype_layoutstr"auto""auto" (quadrants up to four phenotype or carrier sources, bands beyond), "quadrants" (the same, with a warning when it falls back) or "bands" (one band per column)
phenotype_quadrantsdict{}Column name → "top-left", "top-right", "bottom-left" or "bottom-right"; other columns take their conventional or the next free quadrant
show_na_labelsboolTrueWrite “NA” in bands with no data; when false they stay grey with no text, like an “unknown” band
band_textstr"auto"Text in bands and quadrants. "auto": “name: value”, or the value alone, or the value smaller (down to min_font_size, or half font_size), whichever fits the symbol at that height; else none. "name_value": always “name: value” (before 0.7.0). "value": the value alone. "none": no value
pgs_scalestr"zscore""zscore" (default since 0.10.0), "minmax" (raw scores) or "percentile": how a PGS value is placed on its curve
phenotype_labelsdict{}Name shown for a column, e.g. {"SRS": "SRS T-score"}: legend, quadrant key, band text, tooltips. Others show their name with underscores as spaces
legendstr"auto""compact": with quadrants, one shared Affected / Unaffected / Unknown row for the binary columns of the key; "full": one row per column; "auto": compact with quadrants, full with bands; "minimal": compact, no title, no sex symbols, spacing 0.7 (unless set), a one-symbol key whose binary columns are read from a caption under it
legend_titlestr | None"Legend"The legend’s title; null or "" for none
legend_sex_symbolsboolTrueThe “= Male / = Female” row; false drops it
legend_max_widthfloat | str | NoneNoneWidest the legend may be, in cm (8.5) or with a unit ("85mm", "3.3in"); the PGS row grows up to it before wrapping. Unset: the PGS row wraps where the widest other row ends, its score key on the lines below the caption
legend_textdict{}The legend’s fixed wording by role (key_note, shared_binary, affected, unaffected, unknown, pgs, ptdt, male, female, low, high, not_applicable), e.g. for British spelling or another language
legend_bar_widthstr"equal""equal": every gradient and binned bar as wide as the widest; "own": each its own width
legend_spacingfloat1.0Factor on the legend’s row height and gaps, 0.6 to 3 (e.g. 0.7 for print); the figure is as much shorter
show_pgs_valuesboolFalseWrite each PGS value beside its marker, in its color, left of the curve (“+2.1”, the percentile, or the value); the layout makes room
pgs_colorsdict{}Map of PGS column name to hex color for marker line (e.g. {"PGS_autism": "#3498db"}). Unset: #e74c3c for a single PGS column; with several, distinct colors
gradient_rangedict{}Custom min/max for gradient normalization (e.g. {"SRS": [40, 90]}); the legend writes these ends instead of Low / High
gradient_binsdict{}Clinical thresholds: column → ascending cut-offs (e.g. {"SRS": [60, 66, 76], "IQ": [70]}). The band takes one of the steps of the column’s color (a gi_ column the other way) and the legend shows each step with its limits (“< 60”, “60–65”, “66–75”, “≥ 76”)
gradient_bin_label_positionstr | dict"below"Where the legend writes the step names: "below" the limits, or "inside" the colored steps (the limits stay under the bar); for all columns or by column
gradient_bin_labelsdict{}Names of the steps of gradient_bins, one per step from the lowest up (e.g. {"SRS": [null, "mild", "moderate", "severe"]}, null for an unnamed step); written under the limits in the legend and given in the tooltip
gradient_divergingdict{}Tricolor diverging gradient config (e.g. {"IQ": {"min": 40, "mid": 100, "max": 160, "color_low": "#e74c3c", "color_high": "#2ecc71"}})
zero_pad_idsint0Zero-pad individual IDs to this width (0 = no padding, 3 = "001")
radial_gapfloat2.5Radial spacing between concentric rings (circular layout)
base_radiusfloat3.0Radius of first generation ring (circular layout)

JSON Style File Example

{
  "shape_size": 1.0,
  "font_size": 10,
  "outline_color": "#888888",
  "generation_gap": 2.5,
  "dpi": 300,
  "phenotype_colors": {
    "epilepsy": "#e74c3c",
    "IQ": "#3498db"
  },
  "pgs_colors": {
    "PGS_autism": "#3498db",
    "PGS_IQ": "#e74c3c",
    "PGS_ADHD": "#e67e22"
  },
  "gradient_range": {
    "SRS": [40, 90]
  },
  "gradient_diverging": {
    "IQ": {
      "min": 40, "mid": 100, "max": 160,
      "color_low": "#e74c3c", "color_high": "#2ecc71"
    }
  },
  "zero_pad_ids": 3
}

Auto-Scaling

For large pedigrees, the figure size is automatically scaled based on the layout bounds. The fig_width and fig_height values serve as minimums; actual dimensions grow with the number of individuals and generations. The pedigree is drawn at that scale, then the figure is fitted to the drawing: the same small margin (10 pt) on every side of the pedigree, labels and annotations included, the legend right under it, families side by side packed close, and the figure as wide as the pedigree or the legend, whichever is wider. A pedigree drawn into your own ax leaves your figure and axes as they are.

CanRisk Files

Pedigree files saved by the CanRisk tool (BOADICEA model; formats 1 to 4, first line ##CanRisk 4.0) are read directly, from the CLI, parse_pedigree(), parse_pedigree_from_string() and the web app. A file may hold several families. Columns are read by the names of the ##FamID line.

Other header keys (menarche, parity, BMI…) are ignored. A value CanRisk does not allow raises PedigreeParseError naming the line. CanRisk files are read, not written.

GA4GH Phenopackets v2

A Phenopackets v2 JSON file, a whole Family or a bare Pedigree ({"persons": [...]}), is read by the CLI, parse_pedigree(), parse_pedigree_from_string() and the web app: family, IDs, parents, sex (MALE, FEMALE, UNKNOWN_SEX, OTHER_SEX), affectedStatus (AFFECTED, UNAFFECTED, MISSING), the proband (proband.subject.id) and deaths (vitalStatus). camelCase and snake_case names, fields left at their default and enum numbers (Phenopackets numbering: FEMALE = 1, MALE = 2) are accepted. With consanguinousParents, the proband’s parents are drawn with a double line, with a warning when the pedigree holds none of their common ancestors. HPO features and diseases are not drawn.

export_phenopacket_pedigree(pedigree, path) writes a Pedigree message, without phantom parents or duplicates.

Layout Engine

The layout engine computes (x, y) coordinates for all individuals and connection lines. It has no matplotlib dependency and produces pure numeric FamilyLayout objects.

Pipeline

  1. Couple alone in its family — A family holding only two parents, a man and a woman, with no child in the file, is drawn as their couple, father on the left, with a descent line to a “?”. The pedigree itself is not changed.
  2. Assign generations — BFS from founders, children one generation below parents. Partners aligned to same generation, then propagated until every child sits below both parents. A duplicate node stands on the generation of the individual it repeats. Uses a parent→child adjacency index.
  3. Compute horizontal positions — Each union's descendants form a block. Sibling blocks are packed left to right against each other's contours, generation by generation, and every couple is centred over its children. A married twin's partner stands on the outer side of the twin group, so no spouse is drawn between twins. Where two neighbours' labels would overlap (long IDs, a large font_size, long annotations), those two are moved apart by the room their labels need, measured with the character widths of DejaVu Sans at the SVG's scale; labels that fit change nothing.
  4. Break tangled loops — When both partners descend from people in the pedigree (consanguinity, marriages between branches), they are drawn side by side and the second partner's sibship line stretches to reach them. Siblings are ordered so that the two branches of a loop meet, which keeps that line clear in most pedigrees; when both branches come from the same sibship (cousins marrying), those two siblings are kept together, before any sibling who marries into a family placed later. Where it would still overlap another sibship, the partner is drawn twice instead: among their siblings, and as a duplicate next to their partner, joined by a dotted arc, as the nomenclature allows.
  5. Build geometry — Compute node positions, connection edges (relationship, descent, sibship, individual lines), twin connectors, and duplicate arcs. Every line is horizontal or vertical, as the standard nomenclature requires: a single child that is not centred under its parents (possible only in a loop) hangs from a short sibship-level segment rather than a diagonal.
Guarantees Nodes on a row stay at least sibling_gap apart (couple_gap between partners), and further when their labels need it, and the sibship lines of two different couples never overlap, so every child can be traced to its parents. The test suite checks both on every fixture and on generated pedigrees of up to 200 individuals, with and without loops. The same rules apply at every size.

Performance

Pedigree SizeLayout TimeNotes
9 individuals< 1msTypical clinical pedigree
45 individuals< 1msExtended family
100 individuals≈ 1msIncluding loop breaking
200 individuals≈ 2msLarge research pedigree
500 individuals≈ 5msDensely interbred, many loops

Pedigree Symbols

SymbolMeaning
Square □Male
Circle ○Female
Diamond ◇Unknown sex
Filled shapeAffected
Empty shapeUnaffected
Diagonal line through shapeDeceased
Arrow with a “P” at the lower leftProband (index case). The arrow and the “P” are sized from the font, so they keep their shape however small the pedigree is drawn. With tight spacing or large text, the individual on the left is moved just far enough that the “P” does not run into their label; with a PGS curve, the curve's “PGS” caption moves above it
Double horizontal lineConsanguineous union
Broken horizontal lineDissolved/broken union
Patterned sectionCarrier, one pattern per carrier source (NSGC 2022)
Sparser patternObligate carrier (NSGC 2022)
Half-filled shape / center dotCarrier / obligate carrier (legacy notation)
Dashed shape outlinePhantom (inferred) parent
Horizontal bar between twinsMonozygotic twins
V-lines from descent lineDizygotic twins

Data Models

Enums

Sex

Sex.MALE = 1
Male individual (rendered as square).
Sex.FEMALE = 2
Female individual (rendered as circle).
Sex.UNKNOWN = 0
Unknown sex (rendered as diamond).

Phenotype

Phenotype.UNAFFECTED = 1
Unaffected (empty shape).
Phenotype.AFFECTED = 2
Affected (filled shape).
Phenotype.UNKNOWN = 0
Unknown status.

PhenotypeDisplayMode

PhenotypeDisplayMode.AUTO = "auto"
Auto-detect from data (default, no prefix).
PhenotypeDisplayMode.BINARY = "binary"
Binary rendering: color/white/grey bands (b_ prefix).
PhenotypeDisplayMode.GRADIENT = "gradient"
Continuous gradient scale with value labels (g_ prefix).
PhenotypeDisplayMode.OUTLINE = "outline"
Colored shape border when affected (o_ prefix).
PhenotypeDisplayMode.CATEGORICAL = "categorical"
Distinct color per unique string value (c_ prefix).

Notation enums

Pregnancy
ONGOING ("P"), MISCARRIAGE ("SAB"), TERMINATION ("TOP"), ECTOPIC ("ECT"), STILLBIRTH ("SB").
Adoption
IN, OUT.
Childlessness
BY_CHOICE, INFERTILITY.
ReproductiveRole
DONOR ("D"), SURROGATE ("S").
Gender
MAN, WOMAN, NONBINARY: decides the symbol.

They are grouped in Notation (pregnancy, adoption, childlessness, reproductive_role, gender, is_consultand), the notation field of Individual and NodeLayout. NodeLayout also carries notes (text written under the label) and marker_depth (room taken by a childlessness marker); EdgeType.CHILDLESS marks that marker's segments.

TwinType

TwinType.MONOZYGOTIC = "MZ"
Identical twins (horizontal bar connector).
TwinType.DIZYGOTIC = "DZ"
Fraternal twins (plain V-lines).
TwinType.UNKNOWN = "TW"
Unknown zygosity (? marker).

Core Classes

Individual

Represents one person in the pedigree.

sample_id: str
Unique identifier.
family_id: str
Family this individual belongs to.
sex: Sex
Biological sex.
phenotype: Phenotype
Affected/unaffected status.
father_id: str | None
Father's sample_id (None if unknown).
mother_id: str | None
Mother's sample_id (None if unknown).
is_deceased: bool
Deceased marker.
is_proband: bool
Proband/index case marker.
is_phantom: bool
Inferred parent (dashed outline).
is_carrier: bool
Carrier (heterozygous), from the carrier column.
is_obligate_carrier: bool
Obligate carrier, from the carrier column.
twin_info: list[TwinInfo]
Twin relationships.
extra_phenotypes: dict[str, float | None]
Normalized extra phenotype values [0, 1].
extra_phenotypes_raw: dict[str, float | None]
Raw (original) extra phenotype values.
is_founder: bool (property)
True if no known parents.

Union

Represents a mating relationship between two individuals.

partner_ids: tuple[str, str]
The two partner sample IDs.
children_ids: list[str]
Children from this union.
is_consanguinous: bool
Consanguineous relationship (double line).
is_broken: bool
Dissolved relationship (broken line).

Family

A collection of related individuals and their unions.

family_id: str
Family identifier.
individuals: dict[str, Individual]
Map of sample_id → Individual.
unions: list[Union]
All unions in this family.
get_founders() → list[Individual]
Return individuals with no known parents.
get_children(parent_id) → list[Individual]
Return all children of a parent.
get_union_for_parents(father_id, mother_id) → Union | None
Find the union for a parent pair.
get_unions_for_individual(sample_id) → list[Union]
Get all unions involving an individual.

Pedigree

Top-level container holding one or more families.

families: dict[str, Family]
Map of family_id → Family.
phenotype_names: list[str]
Ordered list of extra phenotype names.
family_ids: list[str] (property)
List of all family IDs.
get_family(family_id) → Family | None
Get a family by ID.
subset(family_ids) → Pedigree
Only these families, keeping every phenotype and annotation column, so render_pedigree(ped.subset(["FAM1"])) draws one family with its bands, PGS curves and legend. KeyError for an unknown ID.
source: Pedigree | None
For a subset, the whole pedigree it was taken from.
column_scope: Pedigree (property)
source, or the pedigree itself. Each column's mode, category colors and carrier legend are decided over its individuals, as values are normalised over the whole file, so a subset is drawn as in the figure of the whole file.
individuals() → Iterator[Individual]
Every individual of every family, in order.

Layout Classes

FamilyLayout

Complete layout result for one family.

family_id: str
Family identifier.
nodes: list[NodeLayout]
Positioned individuals.
edges: list[EdgeLayout]
Positioned connection lines.
twin_connectors: list[TwinConnector]
Twin connection geometry.
duplicate_arcs: list[DuplicateArc]
Arcs connecting duplicate nodes.

NodeLayout

individual_id: str
Sample ID.
x: float, y: float
Position coordinates.
sex: Sex
For shape selection.
phenotype: Phenotype
For fill.
label: str
Display text.

EdgeLayout

start: tuple[float, float]
Start point (x, y).
end: tuple[float, float]
End point (x, y).
edge_type: EdgeType
Type: relationship, descent, sibship, or individual.
line_style: LineStyle
Style: solid, double, broken, or dashed.

Gallery

Simple Trio

Simple trio
Father, mother, and affected child

Three Generations

Three generations
Grandparents, parents, and children across three generations

Monozygotic Twins

Monozygotic twins
Monozygotic (identical) twins connected by a horizontal bar

Consanguinity

Consanguinity
First-cousin marriage shown with double relationship line

Standard Notation

Standard notation
Pregnancies and losses, adoption, childlessness, gender identity and the consultand (nomenclature.ped)

Deceased Individuals

Deceased
Deceased individuals marked with diagonal line through shape

Multi-Phenotype with Bands

Multi-phenotype
Three phenotypes displayed as colored bands within each shape

Multi-Phenotype with PGS

PGS
Phenotypes in quadrants combined with PGS Gaussian distribution curves

Annotations with Multi-PGS

Annotations with multi-PGS
Annotations (gene names below IDs), diverging gradient (IQ), multi-PGS (colored markers), and zero-padded IDs

Four Phenotypes in Quadrants

Four phenotypes, one quadrant each
quadrants.ped (synthetic), --phenotype-layout quadrants: autism top left (blue), ADHD top right (yellow), intellectual disability bottom left (red), epilepsy bottom right (purple), and a green outline for sequenced individuals. 316 has no data at all

Several Outline Columns

One border per outline column
outline_rings.ped (synthetic): which data each individual has, in three outline columns (o_WGS, o_WES, o_Array). One border per column an individual is affected in, the first on the outline, the others around it in column order: III-1 has the three, inner orange for WGS. The legend explains it; the SVG tooltip lists them

Five Generations with Loops (81 individuals)

Five-generation pedigree with two loops
multigenerational.ped (synthetic): a first-cousin marriage (401 × 406) and a marriage between two branches (412 × 429), both drawn side by side with no duplicated individual, because each sibship is ordered so the branches of a loop meet. Binary, gradient and carrier bands (drawn with --phenotype-layout bands), both kinds of twins, deceased individuals, a miscarriage and an adoption. Open it with --interactive to zoom in.
Detail of the first-cousin loop
Detail: 401 and 406 are first cousins, grandchildren of 201. Their parents' sibships are ordered so they meet: 401 is the last of his sibship, 406 the first of hers. Their affected children (501, the proband, and 504) are below a double line; 502 is a carrier, 503 a miscarriage.

Error Handling

All pypedigree exceptions inherit from PedigreeError:

ExceptionWhen
PedigreeParseErrorFile parsing failures (bad format, missing columns, invalid values)
PedigreeValidationErrorData validation failures (duplicate IDs, circular references, sex mismatches)
PedigreeLayoutErrorLayout computation failures
PedigreeBatchErrorrender_families(): some families could not be drawn, the others were (.written, .failures)
from pypedigree import parse_pedigree, PedigreeParseError

try:
    ped = parse_pedigree("invalid.ped")
except PedigreeParseError as e:
    print(f"Parse error: {e}")

Invalid Colors

Every color in a style is checked before drawing starts, and all offending values are reported together as a PedigreeError naming the option each came from:

PedigreeError: Invalid color(s) in style: outline_color = '#12345';
phenotype_colors['Epilepsy'] = '#zzzzzz'. Expected hex values like
'#e74c3c' or named colors like 'grey'.

Warnings

Non-fatal diagnostics use dedicated categories, so they can be filtered or escalated independently of other libraries' warnings.

WarningParentWhen emitted
PedigreeWarningUserWarningBase class for all pypedigree warnings
PedigreeStyleWarningPedigreeWarningA style definition contains something unusable, e.g. an unknown option
PedigreeDataWarningPedigreeWarningPedigree data is questionable but still renderable, e.g. a father recorded as female
import warnings
from pypedigree import PedigreeDataWarning, parse_pedigree

# Treat questionable data as a hard failure
warnings.simplefilter("error", PedigreeDataWarning)
ped = parse_pedigree("family.ped")

An unknown key in a style file is ignored, but reported with a suggested spelling — silently dropping a typo is indistinguishable from the option having no effect:

PedigreeStyleWarning: Unknown style option 'phenotype_color' ignored;
did you mean 'phenotype_colors'?

The CLI captures all of these and prints them as Warning: <message> on stderr.