Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 44 additions & 24 deletions dash_bio/component_factory/_manhattan.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@

from .utils import _get_hover_text

# Canonical chromosome sort order for string chromosome columns.
# Chromosomes not in this list are sorted lexicographically after the known ones.
_CHR_SORT_ORDER = (
[str(i) for i in range(1, 23)]
+ ["X", "Y", "MT", "M"]
)

SUGGESTIVE_LINE_LABEL = "suggestive line"
GENOMEWIDE_LINE_LABEL = "genomewide line"

Expand Down Expand Up @@ -46,9 +53,11 @@ def ManhattanPlot(
- genomic base-pair position
- a numeric quantity to plot such as a p-value or zscore
- chrm (string; default 'CHR'): A string denoting the column name for
the chromosome. This column must be float or integer. Minimum
number of chromosomes required is 1. If you have X, Y, or MT
chromosomes, be sure to renumber these 23, 24, 25, etc.
the chromosome. This column may be numeric or string. Minimum
number of chromosomes required is 1. String columns (e.g. '1',
'2', 'X', 'Y', 'MT') are supported and sorted in standard genomic
order (1-22, X, Y, MT) with any remaining labels sorted
lexicographically.
- bp (string; default 'BP'): A string denoting the column name for the
chromosomal position.
- p (string; default 'P'): A string denoting the column name for the
Expand Down Expand Up @@ -175,9 +184,9 @@ def __init__(
- genomic base-pair position
- a numeric quantity to plot such as a p-value or zscore
- chrm (string; default 'CHR'): A string denoting the column name for the
chromosome. This column must be float or integer. Minimum number
of chromosomes required is 1. If you have X, Y, or MT chromosomes,
be sure to renumber these 23, 24, 25, etc.
chromosome. This column may be numeric or string. String chromosome
labels (e.g. '1', 'X', 'Y', 'MT') are sorted in standard genomic order
(1-22, X, Y, MT). Minimum number of chromosomes required is 1.
- bp (string; default 'BP'): A string denoting the column name for the
chromosomal position.
- p (string; default 'P'): A string denoting the column name for the
Expand Down Expand Up @@ -216,11 +225,7 @@ def __init__(
# numeric type
if chrm not in x.columns.values:
raise KeyError("Column %s not found in 'x' data.frame" % chrm)
else:
if not is_numeric_dtype(x[chrm].dtype):
raise TypeError("%s column should be numeric. Do you have "
"'X', 'Y', 'MT', etc? If so change to "
"numbers and try again." % chrm)
# chrm column may be numeric or string; both are supported.

if bp not in x.columns.values:
raise KeyError("Column %s not found in 'x' data.frame" % bp)
Expand Down Expand Up @@ -287,15 +292,26 @@ def __init__(
self.index = 'INDEX'
self.pos = 'POSITION'

# Build a canonical ordering for the chromosome values so that
# string chromosomes (e.g. '1', '2', 'X', 'Y', 'MT') are sorted
# in standard genomic order rather than lexicographically.
def _chr_sort_key(c):
s = str(c)
try:
return (_CHR_SORT_ORDER.index(s), s)
except ValueError:
return (len(_CHR_SORT_ORDER), s)

# unique chromosomes in sorted order
sorted_chrs = sorted(self.data[chrm].unique(), key=_chr_sort_key)

# Fixes the bug where one chromosome is missing by adding a sequential
# index column.
idx = 0
for i in self.data[chrm].unique():
idx = idx + 1
self.data.loc[self.data[chrm] == i, self.index] = int(idx)
# Set the type to be the same as provided for chrm column
self.data[self.index] = \
self.data[self.index].astype(self.data[chrm].dtype)
for idx, chrom_val in enumerate(sorted_chrs, start=1):
self.data.loc[self.data[chrm] == chrom_val, self.index] = int(idx)
# Always keep INDEX as integer regardless of the chrm column dtype so
# that positional arithmetic below is well-defined for string chrm columns.
self.data[self.index] = self.data[self.index].astype(int)

# This section sets up positions and ticks. Ticks should be placed in
# the middle of a chromosome. The new pos column is added that keeps
Expand Down Expand Up @@ -339,14 +355,17 @@ def __init__(
self.data[self.pos] = self.data[self.pos].astype(
self.data[bp].dtype)

# Build tick labels using sorted chromosome order so that labels
# align with the ticks produced above. For crowded plots (>10 chrs)
# suppress every other label; this works for both numeric and string
# chromosome identifiers.
if self.nChr > 10: # To avoid crowded labels
self.ticksLabels = [
t if np.mod(int(t), 2) # Only every two ticks
else ''
for t in self.data[chrm].unique()
chrom_val if idx % 2 != 0 else ''
for idx, chrom_val in enumerate(sorted_chrs, start=1)
]
else:
self.ticksLabels = self.data[chrm].unique() # All the ticks
self.ticksLabels = sorted_chrs # All the ticks

def figure(
self,
Expand Down Expand Up @@ -527,7 +546,7 @@ def figure(
else data[self.pName].values,
mode="markers",
showlegend=showlegend,
name="chr%i" % data[self.chrName].unique(),
name="chr%s" % data[self.chrName].unique()[0],
marker={
'color': col[0],
'size': point_size
Expand Down Expand Up @@ -564,6 +583,7 @@ def figure(
tmp = data[data[self.index] == i]

chromo = tmp[self.chrName].unique() # Get chromosome name
chromo_label = chromo[0] # scalar for trace name

hover_text = _get_hover_text(
tmp,
Expand All @@ -579,7 +599,7 @@ def figure(
else tmp[self.pName].values,
mode="markers",
showlegend=showlegend,
name="Chr%i" % chromo,
name="Chr%s" % chromo_label,
marker={
'color': col[icol],
'size': point_size
Expand Down
102 changes: 102 additions & 0 deletions tests/unit/test_manhattan_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Unit tests for ManhattanPlot string chromosome support (issue #772)."""

import numpy as np
import pandas as pd
import pytest

from dash_bio import ManhattanPlot

# ---------------------------------------------------------------------------
# Shared fixtures
# ---------------------------------------------------------------------------

RNG = np.random.default_rng(42)
N = 300 # rows per test dataframe


def _make_df(chroms, n=N):
"""Return a minimal GWAS-like dataframe with the given chromosome labels."""
chrom_vals = RNG.choice(chroms, n)
return pd.DataFrame(
{
"CHR": chrom_vals,
"BP": RNG.integers(1, 1_000_000, n),
"P": RNG.uniform(1e-10, 1.0, n),
}
)


# ---------------------------------------------------------------------------
# Tests: string chromosome column
# ---------------------------------------------------------------------------


def test_string_chromosomes_no_error():
"""ManhattanPlot must not raise TypeError for a string CHR column."""
df = _make_df(["1", "2", "3", "X", "Y", "MT"])
fig = ManhattanPlot(df, chrm="CHR", bp="BP", p="P", snp=None, gene=None)
assert fig is not None


def test_string_chromosomes_trace_count():
"""One scatter trace per unique chromosome must be produced."""
chroms = ["1", "2", "X", "Y", "MT"]
df = _make_df(chroms)
fig = ManhattanPlot(df, chrm="CHR", bp="BP", p="P", snp=None, gene=None)
# highlight=True adds a highlighted trace; count non-empty chroms only
trace_names = {t.name for t in fig.data}
for c in chroms:
assert any(c in name for name in trace_names), (
f"No trace found for chromosome {c!r}; got {trace_names}"
)


def test_string_chromosomes_tick_labels_genomic_order():
"""X-axis tick labels must follow genomic order: 1,2,...,22,X,Y,MT."""
chroms = ["MT", "X", "2", "1", "Y", "10"]
df = _make_df(chroms)
fig = ManhattanPlot(df, chrm="CHR", bp="BP", p="P", snp=None, gene=None)
tick_labels = list(fig.layout.xaxis.ticktext)
assert tick_labels == ["1", "2", "10", "X", "Y", "MT"], (
f"Expected genomic sort order but got {tick_labels}"
)


def test_string_chromosomes_crowded_label_suppression():
"""With >10 chromosomes, every other tick label must be suppressed."""
chroms = [str(i) for i in range(1, 23)] + ["X", "Y"] # 24 chromosomes
df = _make_df(chroms, n=1000)
fig = ManhattanPlot(df, chrm="CHR", bp="BP", p="P", snp=None, gene=None)
tick_labels = list(fig.layout.xaxis.ticktext)
assert len(tick_labels) == 24
empty = [lbl for lbl in tick_labels if lbl == ""]
assert len(empty) == 12, (
f"Expected 12 suppressed labels for 24 chromosomes, got {len(empty)}"
)


def test_single_string_chromosome():
"""A dataframe with a single string chromosome must produce a valid figure."""
df = _make_df(["X"])
fig = ManhattanPlot(df, chrm="CHR", bp="BP", p="P", snp=None, gene=None)
assert len(fig.data) >= 1


# ---------------------------------------------------------------------------
# Tests: numeric chromosome column (regression — must still work)
# ---------------------------------------------------------------------------


def test_numeric_chromosomes_regression():
"""Numeric chromosome columns must continue to work after the change."""
df = _make_df([1, 2, 3, 4, 5])
fig = ManhattanPlot(df, chrm="CHR", bp="BP", p="P", snp=None, gene=None)
assert fig is not None
assert len(fig.data) >= 1


def test_numeric_chromosomes_tick_count():
"""Tick count must equal the number of unique numeric chromosomes."""
df = _make_df([1, 2, 3])
fig = ManhattanPlot(df, chrm="CHR", bp="BP", p="P", snp=None, gene=None)
assert len(fig.layout.xaxis.tickvals) == 3