diffgrammar 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffgrammar/__init__.py +6 -0
- diffgrammar/adapters/__init__.py +21 -0
- diffgrammar/adapters/peak_npz.py +114 -0
- diffgrammar/align.py +195 -0
- diffgrammar/analysis.py +744 -0
- diffgrammar/attribute.py +445 -0
- diffgrammar/calibrate.py +279 -0
- diffgrammar/cli.py +659 -0
- diffgrammar/cluster.py +439 -0
- diffgrammar/config.py +213 -0
- diffgrammar/contrast.py +223 -0
- diffgrammar/effects.py +317 -0
- diffgrammar/export.py +185 -0
- diffgrammar/expression.py +399 -0
- diffgrammar/jaspar.py +185 -0
- diffgrammar/marginalize/__init__.py +4 -0
- diffgrammar/marginalize/backgrounds.py +107 -0
- diffgrammar/marginalize/cooperativity.py +344 -0
- diffgrammar/marginalize/design.py +209 -0
- diffgrammar/marginalize/plots.py +546 -0
- diffgrammar/marginalize/predictor.py +109 -0
- diffgrammar/marginalize/readout.py +86 -0
- diffgrammar/marginalize/run.py +223 -0
- diffgrammar/marginalize/store.py +191 -0
- diffgrammar/pair_regression.py +323 -0
- diffgrammar/plotting.py +1186 -0
- diffgrammar/scan.py +151 -0
- diffgrammar/selection.py +174 -0
- diffgrammar/seqlets.py +376 -0
- diffgrammar/sequence.py +22 -0
- diffgrammar/summaries.py +140 -0
- diffgrammar/toy.py +129 -0
- diffgrammar/view/__init__.py +0 -0
- diffgrammar/view/app.py +1942 -0
- diffgrammar/view/data.py +1950 -0
- diffgrammar/view/figures.py +400 -0
- diffgrammar/view/network/index.html +232 -0
- diffgrammar/view/network.py +21 -0
- diffgrammar/view/pages.py +257 -0
- diffgrammar/view/tracks/index.html +459 -0
- diffgrammar/view/tracks.py +153 -0
- diffgrammar-0.1.0.dist-info/METADATA +204 -0
- diffgrammar-0.1.0.dist-info/RECORD +47 -0
- diffgrammar-0.1.0.dist-info/WHEEL +5 -0
- diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
- diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
- diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
diffgrammar/plotting.py
ADDED
|
@@ -0,0 +1,1186 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Figures: cluster logos, the motif bubble summary, the cluster report and the walkthrough figures of
|
|
3
|
+
`Analysis`. The marginalization figures are in `diffgrammar.marginalize.plots`.
|
|
4
|
+
|
|
5
|
+
`style()` sets the manuscript defaults (Nature sizing, 9 pt text, thin axes, no top/right spines).
|
|
6
|
+
Colours for the two conditions of a contrast are passed in, so a figure reads the same in every
|
|
7
|
+
project: condition A on the left / negative end, condition B on the right / positive end.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import functools
|
|
12
|
+
from typing import Dict, List, Optional, Sequence, Tuple
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
BASE_COLORS = {'A': '#109648', 'C': '#255C99', 'G': '#F7B32B', 'T': '#D62839'}
|
|
18
|
+
DEFAULT_A, DEFAULT_B = '#3D8B37', '#E8862E'
|
|
19
|
+
EQUAL_COLOR = '#b0b0b0' # seqlets equal in both conditions (sign 0)
|
|
20
|
+
|
|
21
|
+
RC = {
|
|
22
|
+
'font.size': 9, 'axes.titlesize': 10, 'axes.labelsize': 9, 'xtick.labelsize': 8,
|
|
23
|
+
'ytick.labelsize': 8, 'legend.fontsize': 8, 'axes.linewidth': 0.6, 'xtick.major.width': 0.6,
|
|
24
|
+
'ytick.major.width': 0.6, 'xtick.major.size': 3, 'ytick.major.size': 3,
|
|
25
|
+
'axes.spines.top': False, 'axes.spines.right': False, 'figure.dpi': 200, 'savefig.dpi': 300,
|
|
26
|
+
'font.family': 'sans-serif', 'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
|
|
27
|
+
'pdf.fonttype': 42, 'ps.fonttype': 42,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def style():
|
|
32
|
+
import matplotlib.pyplot as plt
|
|
33
|
+
plt.rcParams.update(RC)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def diverging_cmap(color_a: str = DEFAULT_A, color_b: str = DEFAULT_B):
|
|
37
|
+
from matplotlib.colors import LinearSegmentedColormap
|
|
38
|
+
return LinearSegmentedColormap.from_list('a_white_b', [color_a, '#FFFFFF', color_b], N=256)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# -- logos ------------------------------------------------------------------------------------
|
|
42
|
+
def plot_cwm(cwm: np.ndarray, ax, colors: Optional[dict] = None) -> None:
|
|
43
|
+
"""One (L, 4) matrix as a sequence logo, no axes; letters below the line are negative."""
|
|
44
|
+
import logomaker
|
|
45
|
+
logomaker.Logo(pd.DataFrame(cwm, columns=list('ACGT')), ax=ax,
|
|
46
|
+
color_scheme=colors or BASE_COLORS, show_spines=False)
|
|
47
|
+
ax.axhline(0, color='k', linewidth=0.5)
|
|
48
|
+
ax.set_xticks([])
|
|
49
|
+
ax.set_yticks([])
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def plot_cluster_logos(cluster_ids: Sequence[int], consensus: Sequence[np.ndarray], summary: pd.DataFrame,
|
|
53
|
+
hits: Optional[dict] = None, ncols: int = 6, n_show: int = 24):
|
|
54
|
+
"""Grid of consensus logos for the largest clusters, titled with size, sign split and best TFs."""
|
|
55
|
+
import matplotlib.pyplot as plt
|
|
56
|
+
shown = summary.head(n_show)
|
|
57
|
+
nrows = int(np.ceil(len(shown) / ncols))
|
|
58
|
+
fig, axes = plt.subplots(nrows, ncols, figsize=(ncols * 1.2, nrows * 0.95))
|
|
59
|
+
axes = np.atleast_1d(axes).ravel()
|
|
60
|
+
by_id = dict(zip(cluster_ids, consensus))
|
|
61
|
+
for ax, (_, row) in zip(axes, shown.iterrows()):
|
|
62
|
+
cid = int(row['cluster'])
|
|
63
|
+
plot_cwm(by_id[cid], ax)
|
|
64
|
+
tfs = ' / '.join(h['tf'] for h in (hits or {}).get(cid, [])[:2])
|
|
65
|
+
ax.set_title(f'cl{cid} n={row["n_seqlets"]} +{row["n_pos"]}/-{row["n_neg"]}'
|
|
66
|
+
+ (f'/={int(row["n_equal"])}' if row.get('n_equal', 0) else '')
|
|
67
|
+
+ (f'\n{tfs}' if tfs else ''), fontsize=5, pad=1)
|
|
68
|
+
for ax in axes[len(shown):]:
|
|
69
|
+
ax.set_visible(False)
|
|
70
|
+
fig.tight_layout()
|
|
71
|
+
return fig
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# -- motif bubble summary ---------------------------------------------------------------------
|
|
75
|
+
def plot_motif_bubbles(table: pd.DataFrame, motifs: Sequence[str], columns: Sequence[tuple],
|
|
76
|
+
level: str = 'subfamily', logos: Optional[Dict[str, np.ndarray]] = None,
|
|
77
|
+
column_labels: Optional[Sequence[str]] = None, color_a: str = DEFAULT_A,
|
|
78
|
+
color_b: str = DEFAULT_B, label_a: str = 'A', label_b: str = 'B',
|
|
79
|
+
max_size: float = 220.0, effect_lim: Optional[float] = None, color_by: str = 'none',
|
|
80
|
+
ratio: Optional[pd.Series] = None, ratio_label: str = 'log2 prevalence ratio',
|
|
81
|
+
ratio_lim: Optional[float] = None, row_labels: Optional[Dict[str, str]] = None,
|
|
82
|
+
de: Optional[Dict[str, pd.DataFrame]] = None, de_label: str = 'log2FC'):
|
|
83
|
+
"""
|
|
84
|
+
Rows are motifs, columns (set_name, contrast) pairs; bubble area is prevalence (% of regions).
|
|
85
|
+
|
|
86
|
+
color_by 'none' draws grey bubbles; 'effect' colours them by the median signed effect (A colour
|
|
87
|
+
negative, B colour positive). When the region classes were selected on the predicted contrast,
|
|
88
|
+
the effect sign follows the class by construction, so 'none' is the default. `ratio` (motif ->
|
|
89
|
+
value, e.g. the log2 prevalence ratio between two classes) adds a column of coloured squares
|
|
90
|
+
with its own scale, which compares classes without using the sign. An optional logo column
|
|
91
|
+
shows one representative matrix per motif. row_labels (motif -> text) replaces a motif's name. `de` (motif -> gene,
|
|
92
|
+
log2fc, padj of its candidate TFs, see expression.tf_members) adds a column of their fold changes (B over A), those
|
|
93
|
+
with padj < 0.05 named and coloured by direction: B's colour up in B, A's colour up in A.
|
|
94
|
+
"""
|
|
95
|
+
import matplotlib.pyplot as plt
|
|
96
|
+
from matplotlib.colors import TwoSlopeNorm
|
|
97
|
+
|
|
98
|
+
t = table.set_index([level, 'set_name', 'contrast'])
|
|
99
|
+
pct = np.full((len(motifs), len(columns)), np.nan)
|
|
100
|
+
eff = np.full_like(pct, np.nan)
|
|
101
|
+
for i, m in enumerate(motifs):
|
|
102
|
+
for j, (s, c) in enumerate(columns):
|
|
103
|
+
if (m, s, c) in t.index:
|
|
104
|
+
pct[i, j] = t.loc[(m, s, c), 'prevalence_pct']
|
|
105
|
+
eff[i, j] = t.loc[(m, s, c), 'median_effect']
|
|
106
|
+
cmap = diverging_cmap(color_a, color_b)
|
|
107
|
+
vmax = np.nanmax(pct)
|
|
108
|
+
n_col = len(columns) + (1 if ratio is not None else 0)
|
|
109
|
+
|
|
110
|
+
# the figure is as wide as its parts: motif labels (measured), logos, bubble columns, legend and colour bar
|
|
111
|
+
names = [(row_labels or {}).get(m, m) for m in motifs]
|
|
112
|
+
label_w = _text_width(names, 7) + 0.1
|
|
113
|
+
logo_w, bubble_w = (0.9 if logos else 0.0), 0.55 * n_col
|
|
114
|
+
de_w = 1.0 if de else 0.0
|
|
115
|
+
right_w = 1.0 + (0.8 if ratio is not None or color_by == 'effect' else 0.0)
|
|
116
|
+
fig = plt.figure(figsize=(label_w + logo_w + de_w + bubble_w + right_w, max(0.26 + 0.1 * bool(de), 0.26) * len(motifs) + 1.0), constrained_layout=True)
|
|
117
|
+
widths = [w for w in (logo_w, de_w, bubble_w) if w]
|
|
118
|
+
gs = fig.add_gridspec(1, len(widths), width_ratios=widths) if len(widths) > 1 else None
|
|
119
|
+
ax = fig.add_subplot(gs[0, -1]) if gs is not None else fig.add_subplot()
|
|
120
|
+
y = np.arange(len(motifs))[::-1]
|
|
121
|
+
if color_by == 'effect':
|
|
122
|
+
lim = effect_lim or float(np.nanpercentile(np.abs(eff), 90)) or 1.0
|
|
123
|
+
norm = TwoSlopeNorm(vmin=-lim, vcenter=0, vmax=lim)
|
|
124
|
+
for j in range(len(columns)):
|
|
125
|
+
ok = ~np.isnan(pct[:, j])
|
|
126
|
+
c = cmap(norm(np.clip(eff[ok, j], -lim, lim))) if color_by == 'effect' else '#BBBBBB'
|
|
127
|
+
ax.scatter(np.full(ok.sum(), j), y[ok], s=pct[ok, j] / vmax * max_size, c=c,
|
|
128
|
+
edgecolors='#555555', linewidths=0.3)
|
|
129
|
+
labels = list(column_labels or [f'{s}\n{c}' for s, c in columns])
|
|
130
|
+
if ratio is not None:
|
|
131
|
+
r = np.array([ratio.get(m, np.nan) for m in motifs], float)
|
|
132
|
+
rl = ratio_lim or float(np.nanpercentile(np.abs(r), 95)) or 1.0
|
|
133
|
+
rnorm = TwoSlopeNorm(vmin=-rl, vcenter=0, vmax=rl)
|
|
134
|
+
ok = ~np.isnan(r)
|
|
135
|
+
ax.scatter(np.full(ok.sum(), len(columns)), y[ok], s=55, marker='s', c=cmap(rnorm(np.clip(r[ok], -rl, rl))),
|
|
136
|
+
edgecolors='#555555', linewidths=0.3)
|
|
137
|
+
labels.append('Ratio')
|
|
138
|
+
sm = plt.cm.ScalarMappable(norm=rnorm, cmap=cmap)
|
|
139
|
+
cb = fig.colorbar(sm, ax=ax, shrink=0.35, pad=0.02, extend='both')
|
|
140
|
+
cb.set_label(ratio_label, fontsize=7)
|
|
141
|
+
cb.ax.tick_params(labelsize=6)
|
|
142
|
+
elif color_by == 'effect':
|
|
143
|
+
sm = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
|
|
144
|
+
cb = fig.colorbar(sm, ax=ax, shrink=0.35, pad=0.02, extend='both')
|
|
145
|
+
cb.set_label(f'Median effect ({label_b} − {label_a})', fontsize=7)
|
|
146
|
+
cb.ax.tick_params(labelsize=6)
|
|
147
|
+
ax.set_xticks(range(n_col))
|
|
148
|
+
ax.set_xticklabels(labels, fontsize=7)
|
|
149
|
+
ax.set_yticks(y)
|
|
150
|
+
ax.set_yticklabels(names, fontsize=7)
|
|
151
|
+
ax.set_xlim(-0.6, n_col - 0.4)
|
|
152
|
+
ax.set_ylim(-0.7, len(motifs) - 0.3)
|
|
153
|
+
ax.spines[['left', 'bottom']].set_visible(False)
|
|
154
|
+
ax.tick_params(length=0)
|
|
155
|
+
for frac in (0.25, 1.0):
|
|
156
|
+
ax.scatter([], [], s=frac * max_size, c='#DDDDDD', edgecolors='#555555', linewidths=0.3,
|
|
157
|
+
label=f'{frac * vmax:.0f}%')
|
|
158
|
+
ax.legend(title='Regions with motif', loc='upper left', bbox_to_anchor=(1.02, 1.0), frameon=False,
|
|
159
|
+
fontsize=6, title_fontsize=6, labelspacing=1.2)
|
|
160
|
+
if de:
|
|
161
|
+
dax = fig.add_subplot(gs[0, 1 if logos else 0], sharey=ax)
|
|
162
|
+
lim = float(np.ceil(max((np.abs(d['log2fc']).max() for d in de.values() if len(d)), default=1.0) * 1.1))
|
|
163
|
+
for ri, (yi, m) in enumerate(zip(y, motifs)):
|
|
164
|
+
d = de.get(m)
|
|
165
|
+
if d is None or not len(d):
|
|
166
|
+
continue
|
|
167
|
+
v = d['log2fc'].to_numpy(float)
|
|
168
|
+
sig = (d['padj'] < 0.05).to_numpy()
|
|
169
|
+
yj = yi + np.random.default_rng(ri).uniform(-0.28, 0.28, len(d))
|
|
170
|
+
k = int(sig.sum()) # the named ones one above the other, by fold change, so names do not overlap
|
|
171
|
+
yj[np.flatnonzero(sig)[np.argsort(v[sig])]] = yi + (np.linspace(-0.28, 0.28, k) if k > 1 else 0.0)
|
|
172
|
+
col = np.where(v[sig] > 0, color_b, color_a) # up in B in B's colour, up in A in A's
|
|
173
|
+
dax.scatter(v[~sig], yj[~sig], s=5, color='#bdbdbd', linewidths=0, zorder=2)
|
|
174
|
+
dax.scatter(v[sig], yj[sig], s=11, c=col, linewidths=0, zorder=3)
|
|
175
|
+
for g, x_, yy, c_ in zip(d['gene'][sig], v[sig], yj[sig], col):
|
|
176
|
+
dax.text(x_ + (0.06 if x_ >= 0 else -0.06) * lim, yy, g, fontsize=5, color=c_, ha='left' if x_ >= 0 else 'right',
|
|
177
|
+
va='center', fontstyle='italic', clip_on=False)
|
|
178
|
+
dax.axvline(0, color='black', lw=0.3)
|
|
179
|
+
dax.set_xlim(-lim, lim)
|
|
180
|
+
dax.set_xlabel(de_label, fontsize=7)
|
|
181
|
+
dax.tick_params(labelsize=6, labelleft=False, left=False, length=1.5)
|
|
182
|
+
dax.spines[['left']].set_visible(False)
|
|
183
|
+
if not logos:
|
|
184
|
+
dax.tick_params(labelleft=True)
|
|
185
|
+
ax.tick_params(labelleft=False)
|
|
186
|
+
if logos:
|
|
187
|
+
# logos live on an axis that shares y with the bubbles, so row i of both is the same height; the
|
|
188
|
+
# motif labels move to its left so each logo sits between its label and its bubbles
|
|
189
|
+
lax = fig.add_subplot(gs[0, 0], sharey=ax)
|
|
190
|
+
lax.set_xticks([])
|
|
191
|
+
lax.spines[:].set_visible(False)
|
|
192
|
+
lax.tick_params(length=0)
|
|
193
|
+
ax.tick_params(labelleft=False)
|
|
194
|
+
for yi, m in zip(y, motifs):
|
|
195
|
+
if m in logos:
|
|
196
|
+
inset = lax.inset_axes([0.0, yi - 0.4, 1.0, 0.8], transform=lax.get_yaxis_transform())
|
|
197
|
+
plot_cwm(logos[m], inset)
|
|
198
|
+
inset.set_frame_on(False)
|
|
199
|
+
return fig
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
BOX_MARGIN = 0.05 # room beyond the farthest whisker or flier, as a share of its distance from zero
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _box_limit(boxplots: Sequence[dict]) -> float:
|
|
206
|
+
"""
|
|
207
|
+
The half-width of a symmetric axis that shows every horizontal box whole: the farthest whisker end, or flier when
|
|
208
|
+
shown, from zero, read from the drawn artists (so matplotlib's own whisker rule), plus BOX_MARGIN. 1 when nothing drew.
|
|
209
|
+
"""
|
|
210
|
+
reach = [np.nanmax(np.abs(np.asarray(line.get_xdata(), float))) for bp in boxplots
|
|
211
|
+
for line in bp['whiskers'] + bp['fliers'] if len(line.get_xdata())]
|
|
212
|
+
return float(max(reach)) * (1 + BOX_MARGIN) if reach and max(reach) > 0 else 1.0
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _text_width(labels: Sequence[str], size: float) -> float:
|
|
216
|
+
"""Width in inches of the longest label at a font size, from its glyph outlines (no renderer needed)."""
|
|
217
|
+
from matplotlib.font_manager import FontProperties
|
|
218
|
+
from matplotlib.textpath import TextToPath
|
|
219
|
+
prop, ttp = FontProperties(size=size), TextToPath()
|
|
220
|
+
return max((ttp.get_text_width_height_descent(str(s), prop, ismath=False)[0] for s in labels), default=0.0) / 72
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
#: the first ten family colours, picked by hand; family_colors extends them when a figure has more families
|
|
224
|
+
FAMILY_COLORS = ['#2E7D74', '#C2561F', '#7B5EA7', '#8C6D31', '#CC79A7', '#4F8F3C', '#B5892B', '#3D6E8C', '#9B3B5A', '#5C7A29']
|
|
225
|
+
SINGLE_FAMILY_C = '#cfcfcf'
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _lab(rgb) -> np.ndarray:
|
|
229
|
+
"""sRGB in [0, 1], shape (..., 3), to CIELAB (D65 white)."""
|
|
230
|
+
rgb = np.asarray(rgb, float)
|
|
231
|
+
lin = np.where(rgb > 0.04045, ((rgb + 0.055) / 1.055) ** 2.4, rgb / 12.92)
|
|
232
|
+
xyz = lin @ np.array([[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722], [0.0193, 0.1192, 0.9505]]).T
|
|
233
|
+
xyz = xyz / np.array([0.95047, 1.0, 1.08883])
|
|
234
|
+
f = np.where(xyz > (6 / 29) ** 3, np.cbrt(xyz), xyz / (3 * (6 / 29) ** 2) + 4 / 29)
|
|
235
|
+
return np.stack([116 * f[..., 1] - 16, 500 * (f[..., 0] - f[..., 1]), 200 * (f[..., 1] - f[..., 2])], axis=-1)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@functools.lru_cache(maxsize=None)
|
|
239
|
+
def _family_colors(n: int) -> tuple:
|
|
240
|
+
from matplotlib.colors import to_hex, to_rgb
|
|
241
|
+
if n <= len(FAMILY_COLORS):
|
|
242
|
+
return tuple(FAMILY_COLORS[:n])
|
|
243
|
+
g = np.linspace(0, 1, 33)
|
|
244
|
+
cand = np.stack(np.meshgrid(g, g, g, indexing='ij'), axis=-1).reshape(-1, 3)
|
|
245
|
+
lab = _lab(cand)
|
|
246
|
+
chroma = np.hypot(lab[:, 1], lab[:, 2])
|
|
247
|
+
keep = (lab[:, 0] >= 36) & (lab[:, 0] <= 70) & (chroma >= 22) & (chroma <= 65) # the hand-picked ten's range
|
|
248
|
+
cand, lab = cand[keep], lab[keep]
|
|
249
|
+
taken = _lab([to_rgb(c) for c in FAMILY_COLORS + [SINGLE_FAMILY_C]])
|
|
250
|
+
dist = np.linalg.norm(lab[:, None] - taken[None], axis=-1).min(axis=1)
|
|
251
|
+
out = list(FAMILY_COLORS)
|
|
252
|
+
while len(out) < n:
|
|
253
|
+
k = int(np.argmax(dist))
|
|
254
|
+
out.append(to_hex(cand[k]))
|
|
255
|
+
dist = np.minimum(dist, np.linalg.norm(lab - lab[k], axis=1))
|
|
256
|
+
return tuple(out)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def family_colors(n: int) -> list:
|
|
260
|
+
"""
|
|
261
|
+
n distinct colours for n families: FAMILY_COLORS first, then each next colour the candidate farthest (CIELAB
|
|
262
|
+
distance) from every colour already in use and from the single-family grey. Candidates are an sRGB grid kept to the
|
|
263
|
+
lightness (36 to 70) and saturation (22 to 65) of the hand-picked ten, so the extra colours are as muted as the
|
|
264
|
+
first and none is grey, pale or neon. The same n always gives the same colours, so a family list is coloured alike
|
|
265
|
+
in the report and the viewer. Up to 60 families no two colours are closer than the closest two of the first ten.
|
|
266
|
+
"""
|
|
267
|
+
return list(_family_colors(int(n)))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def plot_cooc_counts(labels: Sequence[str], families: Sequence[str], panels: Sequence[dict], title: str = '',
|
|
271
|
+
legend_title: str = 'Grouped and coloured by family', single: str = 'family with one motif here',
|
|
272
|
+
dot_label: str = 'more often together than independence (FDR < 0.05)', ncols: Optional[int] = None,
|
|
273
|
+
color_singles: bool = False, pairs: Optional[Sequence[Sequence[dict]]] = None, max_pairs: int = 4):
|
|
274
|
+
"""
|
|
275
|
+
Motif co-occurrence as absolute region counts, one panel per class. panels: dicts with title, color, with (regions
|
|
276
|
+
carrying each motif), both (n x n regions carrying both) and sig (n x n, +1 where the pair occurs together more
|
|
277
|
+
often than independence). Bars on top: each motif's regions; heatmap: regions carrying both, on one power scale
|
|
278
|
+
(gamma 0.45) for every panel, the diagonal grey; dots: sig > 0; colour strips left of the rows and under the
|
|
279
|
+
columns, against the names: the motifs' families, grey for a family with one motif here, or its own colour with
|
|
280
|
+
color_singles. The figure grows with the number of motifs.
|
|
281
|
+
ncols: panels per row (default all in one row), so that two runs' classes can sit one run above the other, every
|
|
282
|
+
panel on the same motifs; the colour bar is then shorter and centred. pairs: per panel, the pairs to show as
|
|
283
|
+
cards in a column right of it, at most max_pairs, each a dict with i, j (the two motifs' indices), logos (their
|
|
284
|
+
two (L, 4) matrices), names (their two labels), optionally tfs (their best-match TFs, under the logos) and text
|
|
285
|
+
(a line at the bottom); an arrow leads from the pair's cell, which gets a ring, to its card.
|
|
286
|
+
"""
|
|
287
|
+
import matplotlib.pyplot as plt
|
|
288
|
+
from collections import Counter
|
|
289
|
+
from matplotlib.colors import PowerNorm
|
|
290
|
+
n, k_p = len(labels), len(panels)
|
|
291
|
+
ncols = k_p if not ncols else min(ncols, k_p)
|
|
292
|
+
n_rows = -(-k_p // ncols)
|
|
293
|
+
multi = list(dict.fromkeys(families)) if color_singles else [g for g, c in Counter(families).items() if c > 1]
|
|
294
|
+
fam_col = dict(zip(multi, family_colors(len(multi))))
|
|
295
|
+
lab_w = _text_width(labels, 7)
|
|
296
|
+
left, panel_w, gap, cbar = lab_w + 0.25, 0.21 * n + 0.45, 0.8, 0.14 # the gap holds the next bars' axis
|
|
297
|
+
heat_h, bar_h, top, bottom = 0.165 * n + 0.38, 0.85, 0.95, 0.72 * lab_w + 0.3
|
|
298
|
+
top += 0.22 * title.count('\n') # a second title line needs its own room
|
|
299
|
+
cards_of = [list(p)[:max_pairs] for p in pairs] if pairs is not None else [[] for _ in panels]
|
|
300
|
+
cw, ch, cgap = 1.5, 1.05, 0.1 # a card: two logos side by side
|
|
301
|
+
extra = [max([cw + 0.22 for k in range(k_p) if k % ncols == c and cards_of[k]] or [0.0]) for c in range(ncols)]
|
|
302
|
+
row_h = bottom + heat_h + 0.06 + bar_h + top
|
|
303
|
+
slot_x = [left + sum(panel_w + extra[c_] + gap for c_ in range(c)) for c in range(ncols)]
|
|
304
|
+
W = slot_x[-1] + panel_w + extra[-1] + 0.25 + cbar + 0.75
|
|
305
|
+
H = n_rows * row_h
|
|
306
|
+
vmax = max(1, max(int(np.max(p['both'])) for p in panels))
|
|
307
|
+
norm, cmap = PowerNorm(0.45, vmin=0, vmax=vmax), plt.get_cmap('YlGnBu')
|
|
308
|
+
bounds = [i for i in range(1, n) if families[i] != families[i - 1]]
|
|
309
|
+
with plt.rc_context(RC):
|
|
310
|
+
fig = plt.figure(figsize=(W, H))
|
|
311
|
+
for k, pnl in enumerate(panels):
|
|
312
|
+
row, col = divmod(k, ncols)
|
|
313
|
+
x0 = slot_x[col]
|
|
314
|
+
base = (n_rows - 1 - row) * row_h
|
|
315
|
+
y0 = base + bottom
|
|
316
|
+
ax = fig.add_axes((x0 / W, y0 / H, panel_w / W, heat_h / H))
|
|
317
|
+
axb = fig.add_axes((x0 / W, (y0 + heat_h + 0.06) / H, panel_w / W, bar_h / H), sharex=ax)
|
|
318
|
+
marg, col = list(pnl['with']), pnl['color']
|
|
319
|
+
axb.bar(range(n), marg, color=col, width=0.72, linewidth=0)
|
|
320
|
+
top_v = max(max(marg), 1)
|
|
321
|
+
for i, v in enumerate(marg):
|
|
322
|
+
axb.text(i, v + top_v * 0.05, f'{v}', ha='center', va='bottom', fontsize=5.6, color=col, fontweight='bold',
|
|
323
|
+
rotation=90)
|
|
324
|
+
axb.set_ylim(0, top_v * 1.32)
|
|
325
|
+
axb.tick_params(axis='x', bottom=False, labelbottom=False)
|
|
326
|
+
axb.tick_params(axis='y', labelsize=6)
|
|
327
|
+
axb.spines[['top', 'right', 'bottom']].set_visible(False)
|
|
328
|
+
axb.set_ylabel('regions\nwith motif', fontsize=7.5, color=col, linespacing=1.2)
|
|
329
|
+
axb.set_title(pnl['title'], fontsize=12, pad=8, color='#222222', # the class as a light tint behind
|
|
330
|
+
bbox=dict(boxstyle='round,pad=0.3,rounding_size=0.4', fc=col, alpha=0.14, ec='none'))
|
|
331
|
+
im = ax.imshow(np.asarray(pnl['both']), cmap=cmap, norm=norm, aspect='auto')
|
|
332
|
+
for i in range(n):
|
|
333
|
+
ax.add_patch(plt.Rectangle((i - .5, i - .5), 1, 1, color='#d8d8d8'))
|
|
334
|
+
yy, xx = np.nonzero(np.asarray(pnl['sig']) > 0)
|
|
335
|
+
ax.scatter(xx, yy, s=8, c='#16222B', linewidths=0, zorder=4)
|
|
336
|
+
sw, sg = 0.55, 0.22 # family strip width and gap, in cells
|
|
337
|
+
for i, g in enumerate(families): # strips left of the rows, under the columns
|
|
338
|
+
c = fam_col.get(g, SINGLE_FAMILY_C)
|
|
339
|
+
ax.add_patch(plt.Rectangle((i - .5, n - .5 + sg), 1, sw, color=c, clip_on=False, zorder=5))
|
|
340
|
+
ax.add_patch(plt.Rectangle((-.5 - sg - sw, i - .5), sw, 1, color=c, clip_on=False, zorder=5))
|
|
341
|
+
for b in bounds:
|
|
342
|
+
ax.axhline(b - .5, color='white', lw=1.1, zorder=6)
|
|
343
|
+
ax.axvline(b - .5, color='white', lw=1.1, zorder=6)
|
|
344
|
+
ax.set_xlim(-.5 - sg - sw - 0.1, n - 0.5)
|
|
345
|
+
ax.set_ylim(n - .5 + sg + sw + 0.1, -0.5) # the names hang right under the column strip
|
|
346
|
+
cards = cards_of[k]
|
|
347
|
+
if cards: # the pairs as logo cards right of the panel, tied to their cells
|
|
348
|
+
import textwrap
|
|
349
|
+
from matplotlib.patches import ConnectionPatch, FancyBboxPatch
|
|
350
|
+
cards = sorted(cards, key=lambda pr: (min(pr['i'], pr['j']), max(pr['i'], pr['j']))) # by row: no crossings
|
|
351
|
+
cx = x0 + panel_w + 0.22
|
|
352
|
+
top_y = y0 + heat_h + 0.06 + bar_h # the column hangs from the top of the bars
|
|
353
|
+
for m, pr in enumerate(cards):
|
|
354
|
+
cy = top_y - (m + 1) * ch - m * cgap
|
|
355
|
+
card = fig.add_axes((cx / W, cy / H, cw / W, ch / H))
|
|
356
|
+
card.set_axis_off()
|
|
357
|
+
card.add_patch(FancyBboxPatch((0.0, 0.0), 1.0, 1.0, boxstyle='round,pad=0,rounding_size=0.05',
|
|
358
|
+
fc='#f6f6f6', ec='none', transform=card.transAxes, clip_on=False))
|
|
359
|
+
for x_, lg, nm, tf in ((0.04, pr['logos'][0], pr['names'][0], (pr.get('tfs') or (None, None))[0]),
|
|
360
|
+
(0.54, pr['logos'][1], pr['names'][1], (pr.get('tfs') or (None, None))[1])):
|
|
361
|
+
ins = card.inset_axes([x_, 0.27, 0.42, 0.42])
|
|
362
|
+
plot_cwm(lg, ins)
|
|
363
|
+
ins.set_axis_off()
|
|
364
|
+
card.text(x_ + 0.21, 0.72, textwrap.fill(str(nm), 19), ha='center', va='bottom', fontsize=5.4,
|
|
365
|
+
color='#222222', linespacing=1.15, transform=card.transAxes)
|
|
366
|
+
if tf:
|
|
367
|
+
card.text(x_ + 0.21, 0.2, str(tf), ha='center', va='top', fontsize=6, style='italic',
|
|
368
|
+
color='#333333', transform=card.transAxes)
|
|
369
|
+
card.text(0.5, 0.47, '+', ha='center', va='center', fontsize=10, color='#8a8a8a', transform=card.transAxes)
|
|
370
|
+
if pr.get('text'):
|
|
371
|
+
card.text(0.5, 0.03, pr['text'], ha='center', va='bottom', fontsize=5.6, color='#444444',
|
|
372
|
+
transform=card.transAxes)
|
|
373
|
+
i, j = sorted((int(pr['i']), int(pr['j'])))
|
|
374
|
+
ax.scatter([j], [i], s=36, facecolors='none', edgecolors='#16222B', linewidths=0.9, zorder=7)
|
|
375
|
+
fig.add_artist(ConnectionPatch(xyA=(j, i), coordsA='data', axesA=ax, xyB=(0.0, 0.5),
|
|
376
|
+
coordsB='axes fraction', axesB=card, arrowstyle='-|>',
|
|
377
|
+
mutation_scale=6, lw=0.6, color='#16222B', alpha=0.9,
|
|
378
|
+
connectionstyle='arc3,rad=-0.08', zorder=20, clip_on=False))
|
|
379
|
+
ax.set_xticks(range(n), labels, rotation=45, ha='right', fontsize=7)
|
|
380
|
+
ax.set_yticks(range(n), labels if col == 0 else [''] * n, fontsize=7)
|
|
381
|
+
ax.tick_params(length=0)
|
|
382
|
+
for sp in ax.spines.values():
|
|
383
|
+
sp.set_visible(False)
|
|
384
|
+
cb_h = heat_h if n_rows == 1 else 0.6 * heat_h
|
|
385
|
+
cb_y = bottom if n_rows == 1 else (H - cb_h) / 2
|
|
386
|
+
cax = fig.add_axes(((slot_x[-1] + panel_w + extra[-1] + 0.25) / W, cb_y / H, cbar / W, cb_h / H))
|
|
387
|
+
cb = fig.colorbar(im, cax=cax)
|
|
388
|
+
cb.set_label('regions carrying both motifs', fontsize=8.5)
|
|
389
|
+
cb.outline.set_visible(False)
|
|
390
|
+
cb.ax.tick_params(labelsize=7.5)
|
|
391
|
+
h = [plt.Line2D([], [], marker='o', ls='', ms=4.5, mfc='#16222B', mec='none')]
|
|
392
|
+
h += [plt.Rectangle((0, 0), 1, 1, color=fam_col[g]) for g in multi]
|
|
393
|
+
names = [dot_label] + multi
|
|
394
|
+
if not color_singles:
|
|
395
|
+
h.append(plt.Rectangle((0, 0), 1, 1, color=SINGLE_FAMILY_C))
|
|
396
|
+
names.append(single)
|
|
397
|
+
fig.legend(h, names, loc='upper center', ncol=4, frameon=False, fontsize=7.6,
|
|
398
|
+
bbox_to_anchor=(0.5, 0.0), title=legend_title, title_fontsize=8.5)
|
|
399
|
+
if title:
|
|
400
|
+
fig.suptitle(title, fontsize=13, y=1 - 0.12 / H, va='top', linespacing=1.4)
|
|
401
|
+
return fig
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def plot_cluster_report(meta: pd.DataFrame, clusters: Sequence[int], logos: Dict[int, np.ndarray],
|
|
405
|
+
names: Dict[int, str], sets: Sequence[str], contrasts: Sequence[str],
|
|
406
|
+
attributed: Dict[tuple, int], set_labels: Optional[Dict[str, str]] = None,
|
|
407
|
+
color_a: str = DEFAULT_A, color_b: str = DEFAULT_B, label_a: str = 'A', label_b: str = 'B',
|
|
408
|
+
split: Optional[int] = None, row_height: float = 0.42, title: str = '',
|
|
409
|
+
targets: Optional[Dict[tuple, np.ndarray]] = None, target_ref: Optional[Dict[str, float]] = None,
|
|
410
|
+
target_label: str = 'Gene log2FC'):
|
|
411
|
+
"""
|
|
412
|
+
One row per cluster: its logo, then for each region set two panels with one slot per contrast: the
|
|
413
|
+
cluster's seqlets stronger in A, equal in both (grey, when any) and stronger in B (stacked bars, counts
|
|
414
|
+
beside them), and each condition's contribution at those seqlets (mot_max_a, mot_max_b; boxes without
|
|
415
|
+
outliers). attributed: (set, contrast)
|
|
416
|
+
-> regions attributed, for the headers. split: a dotted line after this many rows (stronger in B first).
|
|
417
|
+
targets: (cluster, set) -> the fold changes of the genes of the regions where the cluster has a seqlet, which adds
|
|
418
|
+
a third panel per set, one box per cluster; target_ref: set -> the median over the set's regions, dashed.
|
|
419
|
+
"""
|
|
420
|
+
import matplotlib.pyplot as plt
|
|
421
|
+
from matplotlib.patches import Patch
|
|
422
|
+
n, nc = len(clusters), len(contrasts)
|
|
423
|
+
slot = 0.8 / nc
|
|
424
|
+
pos = [-0.4 + (k + 0.5) * slot for k in range(nc)] # centre of contrast k inside a row
|
|
425
|
+
m = meta[meta['cluster'].isin(clusters) & meta['set_name'].isin(sets) & meta['contrast'].isin(contrasts)]
|
|
426
|
+
groups = dict(list(m.groupby(['cluster', 'set_name', 'contrast'])))
|
|
427
|
+
sizes = m.groupby(['cluster', 'set_name', 'contrast']).size()
|
|
428
|
+
cmax = float(sizes.max()) if len(sizes) else 1.0
|
|
429
|
+
box = dict(showfliers=False, patch_artist=True, manage_ticks=False, orientation='horizontal', widths=slot * 0.34,
|
|
430
|
+
medianprops=dict(color='black', linewidth=0.6), whiskerprops=dict(linewidth=0.5),
|
|
431
|
+
capprops=dict(linewidth=0.5), boxprops=dict(linewidth=0.5))
|
|
432
|
+
|
|
433
|
+
per = 3 if targets is not None else 2 # panels per set
|
|
434
|
+
widths = [1.2] + ([1.0, 1.3, 1.2] if targets is not None else [1.1, 1.4]) * len(sets)
|
|
435
|
+
fig, axes = plt.subplots(1, len(widths), sharey=True, figsize=(sum(widths) + 0.9, row_height * n + 1.5),
|
|
436
|
+
gridspec_kw={'width_ratios': widths}, constrained_layout=True)
|
|
437
|
+
y = np.arange(n)
|
|
438
|
+
drawn, drawn_t = [], []
|
|
439
|
+
lax = axes[0]
|
|
440
|
+
lax.set_yticks(y, [names.get(c, f'cl{c}') for c in clusters], fontsize=7)
|
|
441
|
+
lax.set_ylim(n - 0.5, -0.5)
|
|
442
|
+
lax.set_xticks([])
|
|
443
|
+
lax.spines[:].set_visible(False)
|
|
444
|
+
lax.tick_params(length=0)
|
|
445
|
+
for yi, c in zip(y, clusters):
|
|
446
|
+
inset = lax.inset_axes([0.0, yi - 0.4, 1.0, 0.8], transform=lax.get_yaxis_transform())
|
|
447
|
+
plot_cwm(logos[c], inset)
|
|
448
|
+
inset.set_frame_on(False)
|
|
449
|
+
for j, s in enumerate(sets):
|
|
450
|
+
cax, eax = axes[1 + per * j], axes[2 + per * j]
|
|
451
|
+
tax = axes[3 + per * j] if targets is not None else None
|
|
452
|
+
for ax in (cax, eax) + ((tax,) if tax is not None else ()):
|
|
453
|
+
ax.tick_params(left=False, labelleft=False)
|
|
454
|
+
ax.spines['left'].set_visible(False)
|
|
455
|
+
for yi in y[1::2]:
|
|
456
|
+
ax.axhspan(yi - 0.5, yi + 0.5, color='#F4F4F4', lw=0, zorder=0)
|
|
457
|
+
if split:
|
|
458
|
+
ax.axhline(split - 0.5, color='#999999', lw=0.5, ls=':')
|
|
459
|
+
for i, c in enumerate(clusters):
|
|
460
|
+
for k, ct in enumerate(contrasts):
|
|
461
|
+
g = groups.get((c, s, ct))
|
|
462
|
+
na, neq, nb = ((int((g['sign'] < 0).sum()), int((g['sign'] == 0).sum()), int((g['sign'] > 0).sum()))
|
|
463
|
+
if g is not None else (0, 0, 0))
|
|
464
|
+
cax.barh(i + pos[k], na, height=slot * 0.75, color=color_a, lw=0)
|
|
465
|
+
if neq:
|
|
466
|
+
cax.barh(i + pos[k], neq, left=na, height=slot * 0.75, color=EQUAL_COLOR, lw=0)
|
|
467
|
+
cax.barh(i + pos[k], nb, left=na + neq, height=slot * 0.75, color=color_b, lw=0)
|
|
468
|
+
if na + neq + nb: # each count starts where the one before ends, measured in points
|
|
469
|
+
xy, dx = (na + neq + nb, i + pos[k]), 2.0
|
|
470
|
+
for text, color in ((f'{na}', color_a), (f'{neq}', EQUAL_COLOR), (f'{nb}', color_b)):
|
|
471
|
+
if color == EQUAL_COLOR and not neq:
|
|
472
|
+
continue
|
|
473
|
+
cax.annotate(text, xy, xytext=(dx, 0), textcoords='offset points', color=color, fontsize=5.5,
|
|
474
|
+
va='center')
|
|
475
|
+
dx += 3 + 72 * _text_width([text], 5.5)
|
|
476
|
+
for k, ct in enumerate(contrasts):
|
|
477
|
+
for col, color, side in (('mot_max_a', color_a, -1), ('mot_max_b', color_b, 1)):
|
|
478
|
+
data, ys = [], []
|
|
479
|
+
for i, c in enumerate(clusters):
|
|
480
|
+
g = groups.get((c, s, ct))
|
|
481
|
+
v = g[col].dropna().to_numpy(float) if g is not None else np.array([])
|
|
482
|
+
if len(v):
|
|
483
|
+
data.append(v)
|
|
484
|
+
ys.append(i + pos[k] + side * slot * 0.2)
|
|
485
|
+
if data:
|
|
486
|
+
bp = eax.boxplot(data, positions=ys, **box)
|
|
487
|
+
drawn.append(bp)
|
|
488
|
+
for patch in bp['boxes']:
|
|
489
|
+
patch.set_facecolor(color)
|
|
490
|
+
patch.set_alpha(0.8)
|
|
491
|
+
eax.axvline(0, color='#999999', lw=0.4, zorder=0)
|
|
492
|
+
if tax is not None:
|
|
493
|
+
data, ys = [], []
|
|
494
|
+
for i, c in enumerate(clusters):
|
|
495
|
+
v = np.asarray(targets.get((c, s), []), float)
|
|
496
|
+
v = v[np.isfinite(v)]
|
|
497
|
+
if len(v):
|
|
498
|
+
data.append(v)
|
|
499
|
+
ys.append(i)
|
|
500
|
+
if data:
|
|
501
|
+
bp = tax.boxplot(data, positions=ys, **{**box, 'widths': 0.5})
|
|
502
|
+
drawn_t.append(bp)
|
|
503
|
+
for patch in bp['boxes']:
|
|
504
|
+
patch.set_facecolor(TARGET_COLOR)
|
|
505
|
+
patch.set_alpha(0.85)
|
|
506
|
+
tax.axvline(0, color='#999999', lw=0.4, zorder=0)
|
|
507
|
+
if target_ref and np.isfinite(target_ref.get(s, np.nan)):
|
|
508
|
+
tax.axvline(target_ref[s], color='#555555', lw=0.6, ls='--', zorder=1)
|
|
509
|
+
tax.set_xlabel(target_label)
|
|
510
|
+
cax.set_xlim(0, 1.45 * cmax)
|
|
511
|
+
cax.set_xlabel('Seqlets')
|
|
512
|
+
eax.set_xlabel('Contribution\nat the seqlet' if tax is not None else 'Contribution at the seqlet')
|
|
513
|
+
with_seqlet = [meta.loc[(meta['set_name'] == s) & (meta['contrast'] == ct), 'coord'].nunique() for ct in contrasts]
|
|
514
|
+
info = (f'{with_seqlet[0]:,} of {attributed.get((s, contrasts[0]), 0):,} regions with a seqlet' if nc == 1 else
|
|
515
|
+
'; '.join(f'{ct} {w:,}/{attributed.get((s, ct), 0):,}' for ct, w in zip(contrasts, with_seqlet)))
|
|
516
|
+
cax.set_title(f'{(set_labels or {}).get(s, s)}\n{info}', loc='left', fontsize=8)
|
|
517
|
+
elim = _box_limit(drawn) # every box whole, on one scale across the sets
|
|
518
|
+
for j in range(len(sets)):
|
|
519
|
+
axes[2 + per * j].set_xlim(-elim, elim)
|
|
520
|
+
if targets is not None: # the genes on one scale too, every box whole
|
|
521
|
+
tlim = _box_limit(drawn_t)
|
|
522
|
+
for j in range(len(sets)):
|
|
523
|
+
axes[3 + per * j].set_xlim(-tlim, tlim)
|
|
524
|
+
if nc > 1:
|
|
525
|
+
last = axes[-1]
|
|
526
|
+
for i in y:
|
|
527
|
+
for k, ct in enumerate(contrasts):
|
|
528
|
+
last.text(1.02, i + pos[k], ct, transform=last.get_yaxis_transform(), fontsize=6, va='center')
|
|
529
|
+
handles = [Patch(color=color_a, label=label_a), Patch(color=color_b, label=label_b)]
|
|
530
|
+
if (m['sign'] == 0).any():
|
|
531
|
+
handles.insert(1, Patch(color=EQUAL_COLOR, label='equal in both'))
|
|
532
|
+
fig.legend(handles=handles, loc='outside lower center', ncol=len(handles), frameon=False, fontsize=7)
|
|
533
|
+
if title:
|
|
534
|
+
fig.suptitle(title, fontsize=9)
|
|
535
|
+
return fig
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def plot_contributions(contrib: np.ndarray, seqlets: Sequence[dict], ax, window: Optional[tuple] = None,
|
|
539
|
+
color_a: str = DEFAULT_A, color_b: str = DEFAULT_B, label: str = 'Contribution (B − A)'):
|
|
540
|
+
"""
|
|
541
|
+
Contrast contribution per position as bars (B colour above zero, A colour below), with each
|
|
542
|
+
seqlet's span shaded and its cut drawn as dotted lines.
|
|
543
|
+
"""
|
|
544
|
+
lo, hi = window or (0, len(contrib))
|
|
545
|
+
x = np.arange(lo, hi)
|
|
546
|
+
c = np.asarray(contrib)[lo:hi]
|
|
547
|
+
ax.bar(x, c, width=1.0, color=np.where(c >= 0, color_b, color_a), linewidth=0)
|
|
548
|
+
for s in seqlets:
|
|
549
|
+
if lo <= s['start'] < hi:
|
|
550
|
+
ax.axvspan(s['start'] - 0.5, s['end'] - 0.5, color='#999999', alpha=0.18, lw=0)
|
|
551
|
+
if seqlets:
|
|
552
|
+
cut = seqlets[0]['cut']
|
|
553
|
+
for y in (cut, -cut):
|
|
554
|
+
ax.axhline(y, color='#555555', lw=0.5, ls=':')
|
|
555
|
+
ax.axhline(0, color='black', lw=0.5)
|
|
556
|
+
ax.set_xlim(lo - 0.5, hi - 0.5)
|
|
557
|
+
ax.set_xlabel('Input position (bp)')
|
|
558
|
+
ax.set_ylabel(label)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
# -- walkthrough figures (diffgrammar.analysis) -----------------------------------------------
|
|
562
|
+
def plot_tracks(tracks: Dict[str, np.ndarray], colors: Optional[Dict[str, tuple]] = None, title: str = '',
|
|
563
|
+
width: float = 7.0, row_height: float = 1.3):
|
|
564
|
+
"""
|
|
565
|
+
One contribution track per row over the whole input, sharing the x axis. tracks: label -> (L,);
|
|
566
|
+
colors: label -> (colour below zero, colour above zero), grey by default.
|
|
567
|
+
"""
|
|
568
|
+
import matplotlib.pyplot as plt
|
|
569
|
+
fig, axes = plt.subplots(len(tracks), 1, figsize=(width, row_height * len(tracks) + 0.3), sharex=True,
|
|
570
|
+
constrained_layout=True)
|
|
571
|
+
axes = np.atleast_1d(axes)
|
|
572
|
+
for ax, (label, c) in zip(axes, tracks.items()):
|
|
573
|
+
neg, pos = (colors or {}).get(label, ('#999999', '#444444'))
|
|
574
|
+
plot_contributions(c, [], ax, color_a=neg, color_b=pos, label=label)
|
|
575
|
+
for ax in axes[:-1]:
|
|
576
|
+
ax.set_xlabel('')
|
|
577
|
+
if title:
|
|
578
|
+
axes[0].set_title(title, fontsize=9)
|
|
579
|
+
return fig
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def plot_seqlet_window(contrib: np.ndarray, seqlets: Sequence[dict], window: Optional[tuple] = None,
|
|
583
|
+
color_a: str = DEFAULT_A, color_b: str = DEFAULT_B, label: str = 'Contribution (B − A)',
|
|
584
|
+
title: str = '', width: float = 7.0, height: float = 2.0):
|
|
585
|
+
"""plot_contributions as a figure: one region's contributions with its seqlets shaded and the cut dotted."""
|
|
586
|
+
import matplotlib.pyplot as plt
|
|
587
|
+
fig, ax = plt.subplots(figsize=(width, height), constrained_layout=True)
|
|
588
|
+
plot_contributions(contrib, seqlets, ax, window=window, color_a=color_a, color_b=color_b, label=label)
|
|
589
|
+
if title:
|
|
590
|
+
ax.set_title(title, fontsize=9)
|
|
591
|
+
return fig
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def plot_logo_grid(rows: Sequence[Sequence[tuple]], row_labels: Optional[Sequence[str]] = None,
|
|
595
|
+
width: Optional[float] = None, row_height: float = 0.95, title_size: float = 7):
|
|
596
|
+
"""
|
|
597
|
+
Logos in a grid. rows: a list of rows, each a list of (cwm, title); row_labels name the rows. Letters
|
|
598
|
+
above the line are positive, below negative.
|
|
599
|
+
"""
|
|
600
|
+
import matplotlib.pyplot as plt
|
|
601
|
+
ncol = max(len(r) for r in rows)
|
|
602
|
+
width = width or min(7.0, 1.25 * ncol + 0.2)
|
|
603
|
+
fig, axes = plt.subplots(len(rows), ncol, figsize=(width, row_height * len(rows)), squeeze=False,
|
|
604
|
+
constrained_layout=True)
|
|
605
|
+
for i, row in enumerate(rows):
|
|
606
|
+
for j in range(ncol):
|
|
607
|
+
ax = axes[i, j]
|
|
608
|
+
if j >= len(row):
|
|
609
|
+
ax.set_visible(False)
|
|
610
|
+
continue
|
|
611
|
+
cwm, title = row[j]
|
|
612
|
+
plot_cwm(cwm, ax)
|
|
613
|
+
ax.set_title(title, fontsize=title_size)
|
|
614
|
+
if row_labels:
|
|
615
|
+
axes[i, 0].set_ylabel(row_labels[i], fontsize=7)
|
|
616
|
+
return fig
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
_GLYPHS: Dict[str, object] = {}
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def _glyph(base: str):
|
|
623
|
+
"""The outline of one letter, scaled to the unit square; built once per letter."""
|
|
624
|
+
if base not in _GLYPHS:
|
|
625
|
+
from matplotlib.font_manager import FontProperties
|
|
626
|
+
from matplotlib.textpath import TextPath
|
|
627
|
+
from matplotlib.transforms import Affine2D
|
|
628
|
+
path = TextPath((0, 0), base, size=1, prop=FontProperties(family='DejaVu Sans', weight='bold'))
|
|
629
|
+
bb = path.get_extents()
|
|
630
|
+
_GLYPHS[base] = Affine2D().translate(-bb.x0, -bb.y0).scale(1 / bb.width, 1 / bb.height).transform_path(path)
|
|
631
|
+
return _GLYPHS[base]
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def draw_logo(ax, matrix: np.ndarray, x0: int = 0, colors: Optional[dict] = None, width: float = 0.9):
|
|
635
|
+
"""
|
|
636
|
+
An (L, 4) matrix as a sequence logo on `ax`, position i centred at x0 + i: letters stretched to their value,
|
|
637
|
+
positives stacked up from zero (largest on top), negatives stacked down and drawn upside down, as logomaker
|
|
638
|
+
draws them. One collection for the whole logo, so a 1,000 bp track draws in well under a second.
|
|
639
|
+
"""
|
|
640
|
+
from matplotlib.collections import PathCollection
|
|
641
|
+
from matplotlib.transforms import Affine2D
|
|
642
|
+
colors = colors or BASE_COLORS
|
|
643
|
+
paths, faces = [], []
|
|
644
|
+
for i, col in enumerate(np.asarray(matrix, float)):
|
|
645
|
+
x = x0 + i - width / 2
|
|
646
|
+
up = 0.0
|
|
647
|
+
for v, b in sorted((v, b) for v, b in zip(col, 'ACGT') if v > 0):
|
|
648
|
+
paths.append(Affine2D().scale(width, v).translate(x, up).transform_path(_glyph(b)))
|
|
649
|
+
faces.append(colors[b])
|
|
650
|
+
up += v
|
|
651
|
+
down = 0.0
|
|
652
|
+
for v, b in sorted(((v, b) for v, b in zip(col, 'ACGT') if v < 0), reverse=True):
|
|
653
|
+
paths.append(Affine2D().scale(width, v).translate(x, down).transform_path(_glyph(b)))
|
|
654
|
+
faces.append(colors[b])
|
|
655
|
+
down += v
|
|
656
|
+
coll = PathCollection(paths, facecolors=faces, edgecolors='none', transform=ax.transData, zorder=2)
|
|
657
|
+
ax.add_collection(coll)
|
|
658
|
+
return coll
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def plot_tracks_logos(onehot: np.ndarray, tracks: Dict[str, np.ndarray], seqlets: Sequence[dict] = (),
|
|
662
|
+
window: Optional[tuple] = None, cut: Optional[float] = None, cut_row: Optional[str] = None,
|
|
663
|
+
names: Optional[Sequence[str]] = None, highlight=None,
|
|
664
|
+
row_colors: Optional[Dict[str, str]] = None, share_y: bool = True,
|
|
665
|
+
genomic: Optional[tuple] = None, title: str = '', bp_inch: float = 0.1,
|
|
666
|
+
row_height: float = 1.0, min_width: float = 7.0, ymax: Optional[float] = None):
|
|
667
|
+
"""
|
|
668
|
+
One region as attribution logos: one row per track (the mean A and B contributions and B − A, say), each
|
|
669
|
+
position drawn as the input base stretched to its contribution, on a shared x axis over `window` (lo, hi) in
|
|
670
|
+
input coordinates (default the whole input). Rows share one y scale unless share_y is False.
|
|
671
|
+
|
|
672
|
+
seqlets: dicts with start, end (input coordinates) and, when `highlight` is given, cluster; their spans are
|
|
673
|
+
shaded on every row, the seqlets of cluster `highlight` in colour (an int, or a dict cluster -> colour for
|
|
674
|
+
several), and `names` (one per seqlet) are written above the top row. cut: the seqlet threshold, drawn as dotted lines on `cut_row` (default the last row).
|
|
675
|
+
genomic: (chrom, position of input 0) labels the x axis in genome coordinates. The figure is bp_inch wide per
|
|
676
|
+
base (0.1 inch, 10 px at 100 dpi), so it is meant to be scrolled or saved, not fitted to a page. ymax fixes the
|
|
677
|
+
y scale of every row, for figures of several regions on one scale. A window may
|
|
678
|
+
reach beyond the input: the axis keeps it and the margin stays empty, so logos of several regions drawn with
|
|
679
|
+
windows of one width, centred on a site each, line up on that site.
|
|
680
|
+
"""
|
|
681
|
+
import matplotlib.pyplot as plt
|
|
682
|
+
from matplotlib.ticker import MaxNLocator
|
|
683
|
+
L = len(onehot)
|
|
684
|
+
wlo, whi = (int(window[0]), int(window[1])) if window else (0, L)
|
|
685
|
+
lo, hi = max(0, wlo), min(L, whi) # the data drawn; the axis keeps the window asked for
|
|
686
|
+
labels = list(tracks)
|
|
687
|
+
cut_row = cut_row or labels[-1]
|
|
688
|
+
width = max(min_width, (whi - wlo) * bp_inch)
|
|
689
|
+
fig, axes = plt.subplots(len(labels), 1, figsize=(width, row_height * len(labels) + 0.7), sharex=True,
|
|
690
|
+
constrained_layout=True)
|
|
691
|
+
axes = np.atleast_1d(axes)
|
|
692
|
+
mats = {k: onehot[lo:hi] * np.asarray(v, float)[lo:hi, None] for k, v in tracks.items()}
|
|
693
|
+
vmax_all = max(float(np.abs(m.sum(1)).max()) for m in mats.values()) or 1.0
|
|
694
|
+
shown = [(s, names[k] if names is not None else None) for k, s in enumerate(seqlets)
|
|
695
|
+
if s['end'] > lo and s['start'] < hi]
|
|
696
|
+
hl = {} if highlight is None else highlight if isinstance(highlight, dict) else {int(highlight): '#F2C14E'}
|
|
697
|
+
|
|
698
|
+
def lit(s):
|
|
699
|
+
return hl.get(int(s['cluster'])) if 'cluster' in s and int(s['cluster']) in hl else None
|
|
700
|
+
for ax, label in zip(axes, labels):
|
|
701
|
+
draw_logo(ax, mats[label], x0=lo)
|
|
702
|
+
v = (ymax if ymax else vmax_all if share_y else (float(np.abs(mats[label].sum(1)).max()) or 1.0)) * 1.08
|
|
703
|
+
ax.set_ylim(-v, v)
|
|
704
|
+
ax.set_xlim(wlo - 0.5, whi - 0.5)
|
|
705
|
+
ax.axhline(0, color='black', lw=0.5)
|
|
706
|
+
ax.set_ylabel(label, rotation=0, ha='right', va='center', fontsize=8, fontweight='bold',
|
|
707
|
+
color=(row_colors or {}).get(label, 'black'))
|
|
708
|
+
ax.yaxis.set_major_locator(MaxNLocator(3))
|
|
709
|
+
for s, _ in shown:
|
|
710
|
+
c = lit(s)
|
|
711
|
+
ax.axvspan(s['start'] - 0.5, s['end'] - 0.5, color=c or '#999999', alpha=0.45 if c else 0.18, lw=0, zorder=1)
|
|
712
|
+
if cut is not None and label == cut_row:
|
|
713
|
+
for y in (cut, -cut):
|
|
714
|
+
ax.axhline(y, color='#555555', lw=0.6, ls=':')
|
|
715
|
+
for k, (s, name) in enumerate(shown):
|
|
716
|
+
if name:
|
|
717
|
+
c = lit(s)
|
|
718
|
+
axes[0].text((s['start'] + s['end'] - 1) / 2, 1.02 + 0.12 * (k % 2), name, transform=axes[0].get_xaxis_transform(),
|
|
719
|
+
ha='center', va='bottom', fontsize=6.5, color='black' if c else '#555555',
|
|
720
|
+
fontweight='bold' if c else 'normal', clip_on=False)
|
|
721
|
+
ax = axes[-1]
|
|
722
|
+
n_ticks = max(4, int(width / 1.2))
|
|
723
|
+
if genomic:
|
|
724
|
+
chrom, g0 = genomic
|
|
725
|
+
ticks = MaxNLocator(nbins=n_ticks, steps=[1, 2, 5, 10], integer=True).tick_values(g0 + lo, g0 + hi - 1)
|
|
726
|
+
ticks = ticks[(ticks >= g0 + lo) & (ticks <= g0 + hi - 1)]
|
|
727
|
+
ax.set_xticks(ticks - g0)
|
|
728
|
+
ax.set_xticklabels([f'{int(t):,}' for t in ticks])
|
|
729
|
+
ax.set_xlabel(f'{chrom} (bp)')
|
|
730
|
+
else:
|
|
731
|
+
ax.xaxis.set_major_locator(MaxNLocator(nbins=n_ticks, integer=True))
|
|
732
|
+
ax.set_xlabel('Input position (bp)')
|
|
733
|
+
if title:
|
|
734
|
+
axes[0].set_title(title, fontsize=9, pad=22 if any(n for _, n in shown) else 4, loc='left')
|
|
735
|
+
return fig
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def plot_threshold_sweep(sweep: pd.DataFrame, x: str = 'pct', current: Optional[float] = None,
|
|
739
|
+
xlabel: str = 'pct (fraction of the budget)'):
|
|
740
|
+
"""One panel per column of sweep other than x, each against x; a dotted line marks the current value."""
|
|
741
|
+
import matplotlib.pyplot as plt
|
|
742
|
+
cols = [c for c in sweep.columns if c != x]
|
|
743
|
+
fig, axes = plt.subplots(1, len(cols), figsize=(7.0, 2.0), constrained_layout=True)
|
|
744
|
+
for ax, col in zip(np.atleast_1d(axes), cols):
|
|
745
|
+
ax.plot(sweep[x], sweep[col], marker='o', ms=3, lw=1, color='#333333')
|
|
746
|
+
if current is not None:
|
|
747
|
+
ax.axvline(current, color='#999999', lw=0.6, ls=':')
|
|
748
|
+
ax.set_xlabel(xlabel)
|
|
749
|
+
ax.set_ylabel(col)
|
|
750
|
+
return fig
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def plot_seqlet_overview(meta: pd.DataFrame, sets: Sequence[str], set_labels: Optional[Dict[str, str]] = None,
|
|
754
|
+
set_colors: Optional[Dict[str, str]] = None, color_a: str = DEFAULT_A,
|
|
755
|
+
color_b: str = DEFAULT_B, label_a: str = 'A', label_b: str = 'B', set_col: str = 'set_name',
|
|
756
|
+
directions: Optional[Tuple[str, str]] = None):
|
|
757
|
+
"""
|
|
758
|
+
Seqlets per region set split by direction (stronger in A, equal in both when any, stronger in B; `directions`
|
|
759
|
+
names the two, as lowers / raises in a single-track run), then the length and strength (|mot_max|, of the seqlets
|
|
760
|
+
with a differential) of the seqlets per set.
|
|
761
|
+
"""
|
|
762
|
+
neg, pos = directions or (f'stronger in {label_a}', f'stronger in {label_b}')
|
|
763
|
+
import matplotlib.pyplot as plt
|
|
764
|
+
set_labels = set_labels or {}
|
|
765
|
+
fig, axes = plt.subplots(1, 3, figsize=(7.0, 2.1), constrained_layout=True)
|
|
766
|
+
split = meta.groupby([set_col, 'sign']).size().unstack(fill_value=0).reindex(index=list(sets), columns=[-1, 0, 1],
|
|
767
|
+
fill_value=0)
|
|
768
|
+
x = np.arange(len(sets))
|
|
769
|
+
axes[0].bar(x, split[-1], color=color_a, label=neg)
|
|
770
|
+
if split[0].any():
|
|
771
|
+
axes[0].bar(x, split[0], bottom=split[-1], color=EQUAL_COLOR, label='equal in both')
|
|
772
|
+
axes[0].bar(x, split[1], bottom=split[-1] + split[0], color=color_b, label=pos)
|
|
773
|
+
axes[0].set_xticks(x, [set_labels.get(s, s) for s in sets])
|
|
774
|
+
axes[0].set_ylabel('Seqlets')
|
|
775
|
+
axes[0].legend(frameon=False)
|
|
776
|
+
for s in sets:
|
|
777
|
+
g = meta[meta[set_col] == s]
|
|
778
|
+
kw = dict(histtype='step', color=(set_colors or {}).get(s), label=set_labels.get(s, s))
|
|
779
|
+
axes[1].hist(g['end'] - g['start'], bins=np.arange(3.5, 31.5), **kw)
|
|
780
|
+
axes[2].hist(np.log10(g['mot_max'].abs().dropna()), bins=30, **kw)
|
|
781
|
+
axes[1].set_xlabel('Seqlet length (bp)')
|
|
782
|
+
axes[1].set_ylabel('Seqlets')
|
|
783
|
+
axes[1].legend(frameon=False)
|
|
784
|
+
axes[2].set_xlabel('log10 |mot_max|')
|
|
785
|
+
axes[2].set_ylabel('Seqlets')
|
|
786
|
+
return fig
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def plot_cluster_sizes(summary: pd.DataFrame, n: int = 30, color_a: str = DEFAULT_A, color_b: str = DEFAULT_B,
|
|
790
|
+
label_a: str = 'A', label_b: str = 'B', title: str = '', directions: Optional[Tuple[str, str]] = None):
|
|
791
|
+
"""The n largest clusters of cluster_summary as bars, split into seqlets stronger in A, equal in both (when any) and in B
|
|
792
|
+
(`directions` names the two, as lowers / raises in a single-track run)."""
|
|
793
|
+
neg, pos = directions or (f'stronger in {label_a}', f'stronger in {label_b}')
|
|
794
|
+
import matplotlib.pyplot as plt
|
|
795
|
+
top = summary.head(n)
|
|
796
|
+
fig, ax = plt.subplots(figsize=(7.0, 2.0), constrained_layout=True)
|
|
797
|
+
x = np.arange(len(top))
|
|
798
|
+
neq = top['n_equal'] if 'n_equal' in top else pd.Series(0, index=top.index)
|
|
799
|
+
ax.bar(x, top['n_neg'], color=color_a, label=neg)
|
|
800
|
+
if neq.any():
|
|
801
|
+
ax.bar(x, neq, bottom=top['n_neg'], color=EQUAL_COLOR, label='equal in both')
|
|
802
|
+
ax.bar(x, top['n_pos'], bottom=top['n_neg'] + neq, color=color_b, label=pos)
|
|
803
|
+
ax.set_xticks(x, [f'cl{c}' for c in top['cluster']], rotation=90, fontsize=6)
|
|
804
|
+
ax.set_ylabel('Seqlets')
|
|
805
|
+
if title:
|
|
806
|
+
ax.set_title(title, fontsize=9)
|
|
807
|
+
ax.legend(frameon=False)
|
|
808
|
+
return fig
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def plot_region_selection(cand: pd.DataFrame, label_a: str = 'A', label_b: str = 'B', color_a: str = DEFAULT_A,
|
|
812
|
+
color_b: str = DEFAULT_B, title: str = ''):
|
|
813
|
+
"""
|
|
814
|
+
The attribute step's candidates: measured against predicted B - A difference (or, without measured values, the
|
|
815
|
+
predicted log2 fold change), the kept regions coloured by the condition they favour, the rest grey.
|
|
816
|
+
"""
|
|
817
|
+
import matplotlib.pyplot as plt
|
|
818
|
+
fig, ax = plt.subplots(figsize=(3.5, 3.0), constrained_layout=True)
|
|
819
|
+
kept = cand['selected'].astype(bool)
|
|
820
|
+
if 'pred_b' in cand and 'pred_diff' not in cand: # one condition: measured against predicted signal
|
|
821
|
+
for m, c, lab in ((~kept, '#BBBBBB', f'not kept ({(~kept).sum():,})'), (kept, color_b, f'kept ({kept.sum():,})')):
|
|
822
|
+
if 'meas_b' in cand:
|
|
823
|
+
ax.scatter(cand.loc[m, 'meas_b'], cand.loc[m, 'pred_b'], s=4, color=c, linewidths=0, label=lab,
|
|
824
|
+
rasterized=True)
|
|
825
|
+
else:
|
|
826
|
+
ax.hist(cand.loc[m, 'pred_b'], bins=60, color=c, label=lab)
|
|
827
|
+
ax.set_xlabel(f'Measured {label_b}' if 'meas_b' in cand else f'Predicted {label_b}')
|
|
828
|
+
ax.set_ylabel(f'Predicted {label_b}' if 'meas_b' in cand else 'Regions')
|
|
829
|
+
ax.legend(frameon=False, markerscale=2.5, handletextpad=0.2)
|
|
830
|
+
if title:
|
|
831
|
+
ax.set_title(title)
|
|
832
|
+
return fig
|
|
833
|
+
groups = [(~kept, '#BBBBBB', f'not kept ({(~kept).sum():,})'),
|
|
834
|
+
(kept & (cand['class'] == f'{label_a}_high'), color_a, f'{label_a}-high ({(kept & (cand["class"] == f"{label_a}_high")).sum():,})'),
|
|
835
|
+
(kept & (cand['class'] == f'{label_b}_high'), color_b, f'{label_b}-high ({(kept & (cand["class"] == f"{label_b}_high")).sum():,})')]
|
|
836
|
+
if 'meas_diff' in cand:
|
|
837
|
+
for m, c, lab in groups:
|
|
838
|
+
ax.scatter(cand.loc[m, 'meas_diff'], cand.loc[m, 'pred_diff'], s=4, color=c, linewidths=0, label=lab,
|
|
839
|
+
rasterized=True)
|
|
840
|
+
lim = np.nanmax(np.abs(cand[['meas_diff', 'pred_diff']].to_numpy()))
|
|
841
|
+
ax.plot([-lim, lim], [-lim, lim], color='#555555', lw=0.5, ls=':')
|
|
842
|
+
ax.set_xlabel(f'Measured {label_b} − {label_a}')
|
|
843
|
+
ax.set_ylabel(f'Predicted {label_b} − {label_a}')
|
|
844
|
+
else:
|
|
845
|
+
bins = np.linspace(cand['log2fc'].min(), cand['log2fc'].max(), 60)
|
|
846
|
+
for m, c, lab in groups:
|
|
847
|
+
ax.hist(cand.loc[m, 'log2fc'], bins=bins, color=c, label=lab)
|
|
848
|
+
ax.set_xlabel(f'Predicted log2 fold change, {label_b} / {label_a}')
|
|
849
|
+
ax.set_ylabel('Regions')
|
|
850
|
+
ax.legend(frameon=False, markerscale=2.5, handletextpad=0.2)
|
|
851
|
+
if title:
|
|
852
|
+
ax.set_title(title)
|
|
853
|
+
return fig
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
# -- how the regions and the seqlets were chosen, and motif against motif --------------------------------------------
|
|
857
|
+
TARGET_COLOR = '#54708C'
|
|
858
|
+
STAGE_GREYS = ['#e5e5e5', '#c4c4c4', '#9e9e9e', '#808080', '#6e6e6e', '#585858']
|
|
859
|
+
INCLUDED_C = '#2166ac'
|
|
860
|
+
OUTCOME_COLORS = {'Seqlet called': '#2166ac', 'Above the cut, run too short': '#E07B39', 'No position above the cut': '#FBB98D'}
|
|
861
|
+
CATEGORY_COLORS = ['#D4601A', '#1B7837', '#2166ac', '#7570B3', '#E7298A', '#B8860B', '#17BECF', '#8C564B', '#F5C07A', '#7FC97F']
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def plot_selection_funnel(counts: pd.DataFrame, stages: Sequence[str], sets: Sequence[str], contrasts: Sequence[str],
|
|
865
|
+
set_labels: Optional[Dict[str, str]] = None, width: float = 7.0):
|
|
866
|
+
"""
|
|
867
|
+
Per contrast (columns) and region set (rows), the share of regions each filter removed and the share kept, with the
|
|
868
|
+
number kept beside each bar. counts: contrast, set_name, stage, regions (selection.stage_counts). Sets and contrasts
|
|
869
|
+
without regions are left out.
|
|
870
|
+
"""
|
|
871
|
+
import matplotlib.pyplot as plt
|
|
872
|
+
from matplotlib.patches import Patch
|
|
873
|
+
set_labels = set_labels or {}
|
|
874
|
+
contrasts = [c for c in contrasts if (counts['contrast'] == c).any()]
|
|
875
|
+
sets = [s for s in sets if (counts['set_name'] == s).any()]
|
|
876
|
+
filters = [s for s in stages if s != 'Included']
|
|
877
|
+
colors = {s: STAGE_GREYS[min(k, len(STAGE_GREYS) - 1)] for k, s in enumerate(filters)}
|
|
878
|
+
colors['Included'] = INCLUDED_C
|
|
879
|
+
fig, axes = plt.subplots(1, len(contrasts), figsize=(width, 0.42 * len(sets) + 1.35), sharey=True, squeeze=False, constrained_layout=True)
|
|
880
|
+
y = np.arange(len(sets))
|
|
881
|
+
wide = counts.pivot_table(index=['contrast', 'set_name'], columns='stage', values='regions', aggfunc='sum', fill_value=0)
|
|
882
|
+
total = wide.sum(axis=1)
|
|
883
|
+
for ax, c in zip(axes[0], contrasts):
|
|
884
|
+
left = np.zeros(len(sets))
|
|
885
|
+
rows = [wide.loc[(c, s)] if (c, s) in wide.index else pd.Series(dtype=float) for s in sets]
|
|
886
|
+
n = np.array([float(total.get((c, s), 0)) for s in sets])
|
|
887
|
+
for st in stages:
|
|
888
|
+
frac = np.array([float(r.get(st, 0)) for r in rows]) / np.maximum(n, 1)
|
|
889
|
+
ax.barh(y, frac, left=left, height=0.7, color=colors[st], edgecolor='white', linewidth=0.5)
|
|
890
|
+
left += frac
|
|
891
|
+
for yi, r in zip(y, rows):
|
|
892
|
+
ax.text(1.02, yi, f"{int(r.get('Included', 0)):,}", va='center', ha='left', fontsize=7)
|
|
893
|
+
ax.set_xlim(0, 1)
|
|
894
|
+
ax.set_xticks([0, 0.5, 1])
|
|
895
|
+
ax.set_xticklabels(['0', '50%', '100%'])
|
|
896
|
+
if len(contrasts) > 1:
|
|
897
|
+
ax.set_title(c, pad=10)
|
|
898
|
+
ax.spines['left'].set_visible(False)
|
|
899
|
+
ax.spines['right'].set_visible(False)
|
|
900
|
+
ax.tick_params(axis='y', length=0)
|
|
901
|
+
n_set = counts[counts['contrast'] == contrasts[0]].groupby('set_name')['regions'].sum()
|
|
902
|
+
axes[0, 0].set_yticks(y)
|
|
903
|
+
axes[0, 0].set_yticklabels([f'{set_labels.get(s, s)} (n={int(n_set.get(s, 0)):,})' for s in sets])
|
|
904
|
+
axes[0, 0].invert_yaxis()
|
|
905
|
+
axes[0, len(contrasts) // 2].set_xlabel('Fraction of regions (number kept beside each bar)', fontsize=9)
|
|
906
|
+
fig.legend(handles=[Patch(color=colors[s], label=s) for s in stages], loc='outside lower center',
|
|
907
|
+
ncol=min(len(stages), 5), frameon=False, fontsize=7)
|
|
908
|
+
return fig
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def _log_bins(values: np.ndarray, n: int = 70):
|
|
912
|
+
v = values[np.isfinite(values) & (values > 0)]
|
|
913
|
+
lo = max(np.percentile(v, 0.5), 1e-3 * v.max())
|
|
914
|
+
return lo, np.logspace(np.log10(lo), np.log10(v.max()), n)
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
def plot_predicted_signal(table: pd.DataFrame, null: Optional[pd.DataFrame], sets: Sequence[str], contrasts: Sequence[str],
|
|
918
|
+
label_a: str = 'A', label_b: str = 'B', set_labels: Optional[Dict[str, str]] = None,
|
|
919
|
+
set_colors: Optional[Dict[str, str]] = None, width: float = 7.0):
|
|
920
|
+
"""
|
|
921
|
+
Predicted signal per condition (rows) and contrast (columns): the kept regions of each set against shuffled sequences
|
|
922
|
+
(with the shuffled cutoff, its median dashed and its range across models shaded) when the run has them
|
|
923
|
+
(selection.null_table), else against every candidate.
|
|
924
|
+
"""
|
|
925
|
+
import matplotlib.pyplot as plt
|
|
926
|
+
set_labels, set_colors = set_labels or {}, set_colors or {}
|
|
927
|
+
contrasts = [c for c in contrasts if (table['contrast'] == c).any()]
|
|
928
|
+
conds = [('pred_a', label_a), ('pred_b', label_b)]
|
|
929
|
+
colors = {s: set_colors.get(s, CATEGORY_COLORS[k % len(CATEGORY_COLORS)]) for k, s in enumerate(sets)}
|
|
930
|
+
fig, axes = plt.subplots(2, len(contrasts), figsize=(width, 3.9), sharex='col', squeeze=False, constrained_layout=True)
|
|
931
|
+
handles = {}
|
|
932
|
+
for ci, c in enumerate(contrasts):
|
|
933
|
+
t = table[table['contrast'] == c]
|
|
934
|
+
kept = t[t['stage'] == 'Included'] if 'stage' in t else t
|
|
935
|
+
for ri, (col, cond) in enumerate(conds):
|
|
936
|
+
ax = axes[ri, ci]
|
|
937
|
+
nv = None
|
|
938
|
+
if null is not None:
|
|
939
|
+
g = null[(null['contrast'] == c) & (null['condition'] == cond)]
|
|
940
|
+
nv = g['value'].to_numpy(float) if len(g) else None
|
|
941
|
+
ref = nv if nv is not None else t[col].to_numpy(float)
|
|
942
|
+
parts = [kept.loc[kept['set_name'] == s, col].to_numpy(float) for s in sets]
|
|
943
|
+
lo, bins = _log_bins(np.concatenate([ref, *parts]))
|
|
944
|
+
ref = ref[np.isfinite(ref)]
|
|
945
|
+
h = ax.hist(np.clip(ref, lo, None), bins=bins, weights=np.full(len(ref), 1 / max(len(ref), 1)), color='#bdbdbd')
|
|
946
|
+
handles['Shuffled sequences' if nv is not None else 'All candidates'] = h[2][0]
|
|
947
|
+
for k, (s, v) in enumerate(zip(sets, parts)):
|
|
948
|
+
v = v[np.isfinite(v)]
|
|
949
|
+
if not len(v):
|
|
950
|
+
continue
|
|
951
|
+
h = ax.hist(np.clip(v, lo, None), bins=bins, weights=np.full(len(v), 1 / len(v)), histtype='step', color=colors[s], linewidth=1.0)
|
|
952
|
+
handles[f'{set_labels.get(s, s)}, kept'] = h[2][0]
|
|
953
|
+
ax.text(0.98, 0.95 - 0.1 * k, f'n = {len(v):,}', transform=ax.transAxes, ha='right', va='top', fontsize=7, color=colors[s])
|
|
954
|
+
if nv is not None and 'cut' in g:
|
|
955
|
+
cuts = g['cut'].dropna().unique()
|
|
956
|
+
if len(cuts):
|
|
957
|
+
ax.axvspan(cuts.min(), cuts.max(), color='black', alpha=0.12, linewidth=0)
|
|
958
|
+
handles['Shuffled cutoff'] = ax.axvline(np.median(cuts), color='black', linewidth=0.8, linestyle='--')
|
|
959
|
+
ax.set_xscale('log')
|
|
960
|
+
if ri == 0 and len(contrasts) > 1:
|
|
961
|
+
ax.set_title(c)
|
|
962
|
+
if ri == 1:
|
|
963
|
+
ax.set_xlabel('Predicted signal')
|
|
964
|
+
if ci == 0:
|
|
965
|
+
ax.set_ylabel(f'{cond}\nFraction')
|
|
966
|
+
fig.legend(list(handles.values()), list(handles), loc='outside lower center', ncol=min(len(handles), 5), frameon=False, fontsize=7)
|
|
967
|
+
return fig
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def plot_measured_predicted(table: pd.DataFrame, sets: Sequence[str], stages: Sequence[str], label_a: str = 'A', label_b: str = 'B',
|
|
971
|
+
set_labels: Optional[Dict[str, str]] = None, width: float = 7.0):
|
|
972
|
+
"""One panel per set: measured against predicted B - A of one contrast's regions, coloured by the filter that removed them."""
|
|
973
|
+
import matplotlib.pyplot as plt
|
|
974
|
+
from matplotlib.lines import Line2D
|
|
975
|
+
from matplotlib.ticker import MaxNLocator
|
|
976
|
+
set_labels = set_labels or {}
|
|
977
|
+
sets = [s for s in sets if (table['set_name'] == s).any()]
|
|
978
|
+
filters = [s for s in stages if s != 'Included']
|
|
979
|
+
colors = {s: STAGE_GREYS[min(k + 1, len(STAGE_GREYS) - 1)] for k, s in enumerate(filters)}
|
|
980
|
+
colors.update({'Opposite direction': '#d6604d', 'Included': INCLUDED_C})
|
|
981
|
+
ncol = min(len(sets), 4)
|
|
982
|
+
nrow = int(np.ceil(len(sets) / ncol))
|
|
983
|
+
fig, axes = plt.subplots(nrow, ncol, figsize=(width, 1.85 * nrow + 0.75), sharex=True, sharey=True, squeeze=False, constrained_layout=True)
|
|
984
|
+
v = table[['meas_diff', 'pred_diff']].to_numpy(float)
|
|
985
|
+
lim = float(np.nanpercentile(np.abs(v), 99.5))
|
|
986
|
+
for ax, s in zip(axes.ravel(), sets):
|
|
987
|
+
g = table[table['set_name'] == s]
|
|
988
|
+
for st in [*filters, 'Included']:
|
|
989
|
+
k = g['stage'] == st
|
|
990
|
+
ax.scatter(g.loc[k, 'meas_diff'], g.loc[k, 'pred_diff'], s=2, color=colors[st], linewidths=0, alpha=0.5, rasterized=True)
|
|
991
|
+
ax.axhline(0, color='black', linewidth=0.4)
|
|
992
|
+
ax.axvline(0, color='black', linewidth=0.4)
|
|
993
|
+
ax.plot([-lim, lim], [-lim, lim], color='#555555', linewidth=0.5, linestyle=':')
|
|
994
|
+
ax.set_xlim(-lim, lim)
|
|
995
|
+
ax.set_ylim(-lim, lim)
|
|
996
|
+
ax.xaxis.set_major_locator(MaxNLocator(3))
|
|
997
|
+
ax.yaxis.set_major_locator(MaxNLocator(3))
|
|
998
|
+
ax.set_title(f'{set_labels.get(s, s)} (n={len(g):,})', fontsize=8)
|
|
999
|
+
for ax in axes.ravel()[len(sets):]:
|
|
1000
|
+
ax.set_visible(False)
|
|
1001
|
+
fig.supxlabel(f'Measured {label_b} − {label_a}', fontsize=9)
|
|
1002
|
+
fig.supylabel(f'Predicted {label_b} − {label_a}', fontsize=9)
|
|
1003
|
+
fig.legend(handles=[Line2D([], [], marker='o', linestyle='', markersize=4, color=colors[s], label=s) for s in [*filters, 'Included']],
|
|
1004
|
+
loc='outside upper center', ncol=min(len(filters) + 1, 5), frameon=False, fontsize=7)
|
|
1005
|
+
return fig
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def plot_seqlet_threshold(thresholds: pd.DataFrame, sets: Sequence[str], pct: float, min_size: int,
|
|
1009
|
+
set_labels: Optional[Dict[str, str]] = None, width: float = 7.0):
|
|
1010
|
+
"""
|
|
1011
|
+
One panel per set: each region's seqlet cut against its strongest contribution (thresholds.csv, column `outcome`). Above
|
|
1012
|
+
the diagonal a position passes the cut; a seqlet also needs a run of min_size positions.
|
|
1013
|
+
"""
|
|
1014
|
+
import matplotlib.pyplot as plt
|
|
1015
|
+
from matplotlib.lines import Line2D
|
|
1016
|
+
set_labels = set_labels or {}
|
|
1017
|
+
sets = [s for s in sets if (thresholds['set_name'] == s).any()]
|
|
1018
|
+
ncol = min(len(sets), 4)
|
|
1019
|
+
nrow = int(np.ceil(len(sets) / ncol))
|
|
1020
|
+
fig, axes = plt.subplots(nrow, ncol, figsize=(width, min(width / ncol, 2.4) * nrow + 0.8), sharex=True, sharey=True, squeeze=False, constrained_layout=True)
|
|
1021
|
+
pos = thresholds[(thresholds['cut'] > 0) & (thresholds['max_abs_contribution'] > 0)]
|
|
1022
|
+
lo = min(pos['cut'].quantile(0.001), pos['max_abs_contribution'].quantile(0.001)) * 0.8
|
|
1023
|
+
hi = max(pos['cut'].max(), pos['max_abs_contribution'].max()) * 1.2
|
|
1024
|
+
names = {'Above the cut, run too short': f'Above the cut, run under {min_size} bp'}
|
|
1025
|
+
for ax, s in zip(axes.ravel(), sets):
|
|
1026
|
+
g = pos[pos['set_name'] == s]
|
|
1027
|
+
for o in reversed(list(OUTCOME_COLORS)):
|
|
1028
|
+
k = g['outcome'] == o
|
|
1029
|
+
ax.scatter(g.loc[k, 'cut'], g.loc[k, 'max_abs_contribution'], s=3, color=OUTCOME_COLORS[o], linewidths=0, alpha=0.7, rasterized=True)
|
|
1030
|
+
ax.plot([lo, hi], [lo, hi], color='black', linewidth=0.5, linestyle='--')
|
|
1031
|
+
ax.set_xscale('log')
|
|
1032
|
+
ax.set_yscale('log')
|
|
1033
|
+
ax.set_xlim(lo, hi)
|
|
1034
|
+
ax.set_ylim(lo, hi)
|
|
1035
|
+
n = (g['outcome'] == 'Seqlet called').sum()
|
|
1036
|
+
ax.set_title(f'{set_labels.get(s, s)}\n{n:,} of {len(g):,} with a seqlet', fontsize=7)
|
|
1037
|
+
for ax in axes.ravel()[len(sets):]:
|
|
1038
|
+
ax.set_visible(False)
|
|
1039
|
+
fig.supxlabel(f'Seqlet cut ({pct:g} × |budget|)', fontsize=9)
|
|
1040
|
+
fig.supylabel('Strongest |contribution| in the region', fontsize=9)
|
|
1041
|
+
fig.legend(handles=[Line2D([], [], marker='o', linestyle='', markersize=4, color=c, label=names.get(o, o)) for o, c in OUTCOME_COLORS.items()],
|
|
1042
|
+
loc='outside upper center', ncol=3, frameon=False, fontsize=7)
|
|
1043
|
+
return fig
|
|
1044
|
+
|
|
1045
|
+
|
|
1046
|
+
def effect_scale(values) -> dict:
|
|
1047
|
+
"""Colour scale of a numeric column: centred on zero when it takes both signs, sequential otherwise; 2nd to 98th percentile."""
|
|
1048
|
+
v = pd.to_numeric(pd.Series(values), errors='coerce').dropna().to_numpy(float)
|
|
1049
|
+
if len(v) and v.min() < 0 < v.max():
|
|
1050
|
+
lim = float(np.quantile(np.abs(v), 0.98)) or 1.0
|
|
1051
|
+
return {'vmin': -lim, 'vmax': lim, 'cmap': 'RdBu_r', 'diverging': True}
|
|
1052
|
+
lo, hi = (np.quantile(v, [0.02, 0.98]) if len(v) else (0.0, 1.0))
|
|
1053
|
+
return {'vmin': float(lo), 'vmax': float(hi if hi > lo else lo + 1), 'cmap': 'viridis', 'diverging': False}
|
|
1054
|
+
|
|
1055
|
+
|
|
1056
|
+
def category_colors(values, fixed: Optional[Dict[str, str]] = None, max_levels: int = 9) -> Dict[str, str]:
|
|
1057
|
+
"""value -> colour, most frequent first; beyond max_levels, and without a colour given, values turn grey."""
|
|
1058
|
+
fixed = fixed or {}
|
|
1059
|
+
levels = list(pd.Series(values).value_counts().index)
|
|
1060
|
+
free = iter(c for c in CATEGORY_COLORS if c not in fixed.values())
|
|
1061
|
+
out = {}
|
|
1062
|
+
for k, v in enumerate(levels):
|
|
1063
|
+
out[v] = fixed.get(v) or (next(free, '#AAAAAA') if k < max_levels else '#BBBBBB')
|
|
1064
|
+
return out
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def plot_effect_scatter(table: pd.DataFrame, panels: Sequence[str], rows: Sequence[tuple], x_label: str, y_label: str,
|
|
1068
|
+
set_labels: Optional[Dict[str, str]] = None, line: str = 'sum', width: float = 7.0):
|
|
1069
|
+
"""
|
|
1070
|
+
One motif's effect against another's per region (effects.pair_effects): one panel per region set (columns), one row
|
|
1071
|
+
per way of colouring the same points. rows: (column, label, colours of its categories). Numeric columns get a shared
|
|
1072
|
+
colour bar (effect_scale), the most extreme points drawn last. Axes are symmetric and shared; the red line marks where
|
|
1073
|
+
the two effects cancel (line='sum': x + y = 0), or where they are equal ('equal', for one condition's effects).
|
|
1074
|
+
"""
|
|
1075
|
+
import matplotlib.pyplot as plt
|
|
1076
|
+
from matplotlib.lines import Line2D
|
|
1077
|
+
set_labels = set_labels or {}
|
|
1078
|
+
panel_w = min(width / max(len(panels), 1), 3.5)
|
|
1079
|
+
legends = any(not pd.api.types.is_numeric_dtype(table[c]) for c, _, _ in rows)
|
|
1080
|
+
fig, axes = plt.subplots(len(rows), len(panels), figsize=(panel_w * len(panels) + (2.0 if legends else 0), (panel_w + 0.6) * len(rows)), sharex=True,
|
|
1081
|
+
sharey=True, squeeze=False, constrained_layout=True)
|
|
1082
|
+
xy = table[['x', 'y']].to_numpy(float)
|
|
1083
|
+
lim = float(np.abs(np.nanpercentile(xy, [1, 99], axis=0)).max()) * 1.1 or 1.0
|
|
1084
|
+
ends = ([-lim, lim], [lim, -lim]) if line == 'sum' else ([-lim, lim], [-lim, lim])
|
|
1085
|
+
for ri, (col, label, fixed) in enumerate(rows):
|
|
1086
|
+
numeric = pd.api.types.is_numeric_dtype(table[col])
|
|
1087
|
+
scale = effect_scale(table[col]) if numeric else None
|
|
1088
|
+
colors = category_colors(table[col].dropna(), fixed) if not numeric else None
|
|
1089
|
+
sc = None
|
|
1090
|
+
for ci, s in enumerate(panels):
|
|
1091
|
+
ax = axes[ri, ci]
|
|
1092
|
+
g = table[table['set_name'] == s]
|
|
1093
|
+
ax.axhline(0, color='#999999', linewidth=0.4, linestyle='--')
|
|
1094
|
+
ax.axvline(0, color='#999999', linewidth=0.4, linestyle='--')
|
|
1095
|
+
ax.plot(*ends, color='#B2182B', linewidth=0.8)
|
|
1096
|
+
if numeric:
|
|
1097
|
+
g = g.dropna(subset=[col]).sort_values(col, key=np.abs if scale['diverging'] else None)
|
|
1098
|
+
sc = ax.scatter(g['x'], g['y'], c=g[col], cmap=scale['cmap'], vmin=scale['vmin'], vmax=scale['vmax'], s=10, alpha=0.8,
|
|
1099
|
+
edgecolors='none', rasterized=True)
|
|
1100
|
+
else:
|
|
1101
|
+
for v in reversed(list(colors)):
|
|
1102
|
+
k = g[col] == v
|
|
1103
|
+
ax.scatter(g.loc[k, 'x'], g.loc[k, 'y'], color=colors[v], s=10, alpha=0.6, edgecolors='none', rasterized=True)
|
|
1104
|
+
ax.set_xlim(-lim, lim)
|
|
1105
|
+
ax.set_ylim(-lim, lim)
|
|
1106
|
+
ax.set_box_aspect(1)
|
|
1107
|
+
if ri == 0:
|
|
1108
|
+
ax.set_title(f'{set_labels.get(s, s)} (n = {len(table[table["set_name"] == s]):,})', fontsize=8)
|
|
1109
|
+
if ri == len(rows) - 1:
|
|
1110
|
+
ax.set_xlabel(x_label, fontsize=8)
|
|
1111
|
+
if ci == 0:
|
|
1112
|
+
ax.set_ylabel(y_label, fontsize=8)
|
|
1113
|
+
ax.tick_params(labelsize=7)
|
|
1114
|
+
if numeric:
|
|
1115
|
+
cb = fig.colorbar(sc, ax=axes[ri, :], location='bottom', shrink=0.45, aspect=28)
|
|
1116
|
+
cb.set_label(label, fontsize=7)
|
|
1117
|
+
cb.ax.tick_params(labelsize=6.5)
|
|
1118
|
+
else:
|
|
1119
|
+
names = list(colors)[:10]
|
|
1120
|
+
handles = [Line2D([], [], marker='s', linestyle='', markersize=5, color=colors[v], label=v) for v in names]
|
|
1121
|
+
axes[ri, -1].legend(handles=handles, loc='center left', bbox_to_anchor=(1.02, 0.5), frameon=False, fontsize=7, title=label,
|
|
1122
|
+
title_fontsize=7)
|
|
1123
|
+
return fig
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
def plot_motif_targets(table: pd.DataFrame, values: Dict[tuple, np.ndarray], motifs: Sequence[str], sets: Sequence[str], all_label: str,
|
|
1127
|
+
logos: Optional[Dict[str, np.ndarray]] = None, set_labels: Optional[Dict[str, str]] = None,
|
|
1128
|
+
label: str = 'log2FC of the assigned genes', width: float = 7.0):
|
|
1129
|
+
"""
|
|
1130
|
+
One row per motif, one panel per set: the fold change of the genes assigned to the regions carrying the motif (boxes
|
|
1131
|
+
without outliers, n genes beside them). Beside the number, * when BH q < 0.05 against zero and † when BH q < 0.05 against the
|
|
1132
|
+
set's other genes, the row then in bold. The first row is every region of the set, and its median runs down the panel.
|
|
1133
|
+
"""
|
|
1134
|
+
import matplotlib.pyplot as plt
|
|
1135
|
+
set_labels = set_labels or {}
|
|
1136
|
+
rows = [all_label, *motifs]
|
|
1137
|
+
t = table.set_index(['motif', 'set_name'])
|
|
1138
|
+
label_w = _text_width(rows, 7) + 0.1
|
|
1139
|
+
fig = plt.figure(figsize=(max(width, label_w + 0.8 + 2.2 * len(sets)), 0.27 * len(rows) + 0.95), constrained_layout=True)
|
|
1140
|
+
gs = fig.add_gridspec(1, len(sets) + 1, width_ratios=[0.8] + [2.2] * len(sets))
|
|
1141
|
+
lax = fig.add_subplot(gs[0, 0])
|
|
1142
|
+
y = np.arange(len(rows))[::-1]
|
|
1143
|
+
panels, drawn = [], []
|
|
1144
|
+
for si, s in enumerate(sets):
|
|
1145
|
+
ax = fig.add_subplot(gs[0, si + 1], sharey=lax)
|
|
1146
|
+
panels.append(ax)
|
|
1147
|
+
data = [values.get((m, s), np.array([])) for m in rows]
|
|
1148
|
+
keep = [k for k, v in enumerate(data) if len(v)]
|
|
1149
|
+
if keep:
|
|
1150
|
+
bp = ax.boxplot([data[k] for k in keep], positions=y[keep], orientation='horizontal', widths=0.55, showfliers=False, patch_artist=True, manage_ticks=False,
|
|
1151
|
+
medianprops=dict(color='black', linewidth=0.6), whiskerprops=dict(linewidth=0.5), capprops=dict(linewidth=0.5), boxprops=dict(linewidth=0.5))
|
|
1152
|
+
drawn.append(bp)
|
|
1153
|
+
for k, box in zip(keep, bp['boxes']):
|
|
1154
|
+
box.set_facecolor('#BBBBBB' if rows[k] == all_label else TARGET_COLOR)
|
|
1155
|
+
box.set_alpha(0.85)
|
|
1156
|
+
ref = t['median'].get((all_label, s), np.nan)
|
|
1157
|
+
ax.axvline(0, color='black', lw=0.4)
|
|
1158
|
+
if np.isfinite(ref):
|
|
1159
|
+
ax.axvline(ref, color='#999999', lw=0.6, ls='--')
|
|
1160
|
+
for yi, m in zip(y, rows):
|
|
1161
|
+
if (m, s) not in t.index:
|
|
1162
|
+
continue
|
|
1163
|
+
r = t.loc[(m, s)]
|
|
1164
|
+
star = '*' if np.isfinite(r['q']) and r['q'] < 0.05 else ''
|
|
1165
|
+
dagger = '†' if np.isfinite(r['q_rest']) and r['q_rest'] < 0.05 else ''
|
|
1166
|
+
ax.text(1.0, yi, f"{int(r['genes']):,}{star}{dagger}", transform=ax.get_yaxis_transform(), ha='left', va='center', fontsize=6,
|
|
1167
|
+
color=TARGET_COLOR if dagger else '#555555', fontweight='bold' if dagger else 'normal')
|
|
1168
|
+
ax.set_title(set_labels.get(s, s), fontsize=8)
|
|
1169
|
+
ax.tick_params(labelleft=False, left=False, labelsize=7)
|
|
1170
|
+
ax.spines[['left']].set_visible(False)
|
|
1171
|
+
ax.set_xlabel(label, fontsize=7)
|
|
1172
|
+
lim = _box_limit(drawn) # every box whole, on one scale across the sets
|
|
1173
|
+
for ax in panels:
|
|
1174
|
+
ax.set_xlim(-lim, lim)
|
|
1175
|
+
lax.set_yticks(y)
|
|
1176
|
+
lax.set_yticklabels(rows, fontsize=7)
|
|
1177
|
+
lax.set_ylim(-0.7, len(rows) - 0.3)
|
|
1178
|
+
lax.set_xticks([])
|
|
1179
|
+
lax.spines[:].set_visible(False)
|
|
1180
|
+
lax.tick_params(length=0)
|
|
1181
|
+
for yi, m in zip(y, rows):
|
|
1182
|
+
if logos and m in logos:
|
|
1183
|
+
inset = lax.inset_axes([0.0, yi - 0.4, 1.0, 0.8], transform=lax.get_yaxis_transform())
|
|
1184
|
+
plot_cwm(logos[m], inset)
|
|
1185
|
+
inset.set_frame_on(False)
|
|
1186
|
+
return fig
|