easy-volcano 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.
@@ -0,0 +1,771 @@
1
+ Metadata-Version: 2.5
2
+ Name: easy_volcano
3
+ Version: 0.1.0
4
+ Summary: Volcano plots for gene differential-expression results.
5
+ Project-URL: Homepage, https://github.com/rLannes/easy_volcano
6
+ Project-URL: Issues, https://github.com/rLannes/easy_volcano/issues
7
+ Author-email: Romain Lannes <romain.lannes@protonmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: DESeq2,bioinformatics,differential expression,matplotlib,volcano plot
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
16
+ Classifier: Topic :: Scientific/Engineering :: Visualization
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: adjusttext>=1.4
19
+ Requires-Dist: matplotlib>=3.10.9
20
+ Requires-Dist: numpy>=2.2.6
21
+ Requires-Dist: pandas>=2.3.3
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=7; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # easy_volcano
27
+
28
+ Fully customisable, publication-ready volcano plots in one line of Python.
29
+
30
+ Romain JSB Lannes, PhD
31
+
32
+ Volcano plots are used in almost every RNA-seq analysis, yet in Python there are few alternatives to writing
33
+ custom plotting code each time. easy_volcano draws a clean volcano plot in one line, and lets you customise
34
+ every part of it when you need to: colours, labels, legend, extra lines, and any matplotlib option.
35
+
36
+ Example figure:
37
+ ![Volcano plot of the airway dataset with glucocorticoid targets and collagens highlighted](data/figures/hero.png)
38
+
39
+
40
+
41
+ ## Installation
42
+
43
+ easy_volcano is on PyPI.
44
+
45
+ ```bash
46
+ pip install easy_volcano
47
+ ```
48
+
49
+ ## Quick start
50
+
51
+ ```python
52
+ import pandas as pd
53
+ import matplotlib.pyplot as plt
54
+ import easy_volcano as ev
55
+
56
+ df = pd.read_csv("data/easy_volcano_airway_example.tsv", sep="\t") # a DESeq2 results table
57
+ fig, ax = ev.plot_volcano(df)
58
+ plt.show()
59
+ ```
60
+
61
+ By default easy_volcano uses the DESeq2 column names (`log2FoldChange` and `padj`).
62
+ For other tools, pass the column names with `x=` and `y=`, for example `x="logFC", y="adj.P.Val"` for limma.
63
+
64
+ ## Almost endless customisation
65
+
66
+ Most customisation goes through `highlights`, a list of `(which genes, how to draw them)` pairs:
67
+
68
+ ```python
69
+ ev.plot_volcano(df, highlights=[(["FKBP5", "PER1"], {"color": "purple", "size": 200, "label": "my genes"})])
70
+ ```
71
+
72
+ - **Which genes**: a list of gene names, a rule such as `lambda d: d["baseMean"] < 100`, or a True/False column.
73
+ - **How to draw them**: any option of matplotlib's `scatter` (`color`, `size`, `marker`, `edgecolors`, ...),
74
+ plus `label` to add the group to the legend and `label_gene` to write the gene names on the plot.
75
+
76
+ See [How highlights work](#how-highlights-work) and [the `{...}` pattern](#the-pattern-options-passed-to-matplotlib)
77
+ below for the full explanation.
78
+
79
+ ## Examples
80
+
81
+ <!-- examples:start -->
82
+
83
+ All examples use the *airway* RNA-seq dataset (DESeq2 results, the same dataset as the EnhancedVolcano vignette), included in [`data/easy_volcano_airway_example.tsv`](data/easy_volcano_airway_example.tsv). The same code is available as a notebook: [`data/Examples_notebook.ipynb`](data/Examples_notebook.ipynb).
84
+
85
+ ### Contents
86
+
87
+ 1. [Simple plot](#simple-plot)
88
+ - [Load the data](#load-the-data)
89
+ - [Default plot](#default-plot)
90
+ 2. [Customisation](#customisation)
91
+ - [Legend position, label column and number of labels](#legend-position-label-column-and-number-of-labels)
92
+ - [Thresholds and custom lines](#thresholds-and-custom-lines)
93
+ - [Default colours and marker](#default-colours-and-marker)
94
+ - [How highlights work](#how-highlights-work)
95
+ - [The `{...}` pattern: options passed to matplotlib](#the-pattern-options-passed-to-matplotlib)
96
+ - [Custom colours with highlights](#custom-colours-with-highlights)
97
+ - [Highlight low expression genes](#highlight-low-expression-genes)
98
+ - [Spotlight](#spotlight)
99
+ 3. [Going further](#going-further)
100
+ - [Several panels and clipping p-values](#several-panels-and-clipping-p-values)
101
+ - [Master example](#master-example)
102
+ - [Label the genes you care about](#label-the-genes-you-care-about)
103
+ - [Highlight with a rule over any columns](#highlight-with-a-rule-over-any-columns)
104
+ - [Layered highlights: later wins](#layered-highlights-later-wins)
105
+ - [Keep going with matplotlib](#keep-going-with-matplotlib)
106
+ - [Export for Illustrator](#export-for-illustrator)
107
+ 4. [All options](#all-options)
108
+
109
+ <a id="simple-plot"></a>
110
+
111
+ ### Simple plot
112
+
113
+ <a id="load-the-data"></a>
114
+
115
+ #### Load the data
116
+
117
+ ```python
118
+ import easy_volcano as ev
119
+ import pandas as pd
120
+ import numpy as np
121
+ import matplotlib.pyplot as plt
122
+ from pathlib import Path
123
+
124
+ df = pd.read_csv("data/easy_volcano_airway_example.tsv", sep='\t')
125
+ df["gene_name"] = df.index
126
+ ```
127
+
128
+ <a id="default-plot"></a>
129
+
130
+ #### Default plot
131
+
132
+ By default the 5 most over- and under-expressed genes are labelled.
133
+ The adjusted p-value cutoff is 1e-2 by default; airway has a very strong signal, so we use 1e-6 here.
134
+
135
+ ```python
136
+ (fig, ax) = ev.plot_volcano(df, y_thr=10**(-6), title="airway")
137
+ plt.show()
138
+ ```
139
+
140
+ ![default](data/figures/default.png)
141
+
142
+ <a id="customisation"></a>
143
+
144
+ ### Customisation
145
+
146
+ <a id="legend-position-label-column-and-number-of-labels"></a>
147
+
148
+ #### Legend position, label column and number of labels
149
+
150
+ - `legend_loc` has three presets: `"top"`, `"bottom"` and `"right"`. More options are available through `legend_kwargs`.
151
+ - Labels use the index by default, but any column can be used instead with `label_column="gene_name"`.
152
+ - `label_top` labels the top X up- and down-regulated genes.
153
+
154
+ ```python
155
+ (fig, ax) = ev.plot_volcano(df, y_thr=10**(-6), title="airway",
156
+ subtitle="legend on the right, top 10 labels", legend_loc='right', width=8,
157
+ label_column="gene_name", label_top = 10)
158
+ plt.show()
159
+ ```
160
+
161
+ ![legend right label top](data/figures/legend_right_label_top.png)
162
+
163
+ <a id="thresholds-and-custom-lines"></a>
164
+
165
+ #### Thresholds and custom lines
166
+
167
+ Changing a threshold moves both the threshold lines and the colours.
168
+ You can also add your own horizontal or vertical lines by passing a dictionary, or a list of dictionaries,
169
+ with the position (`x` or `y`) plus any matplotlib line option.
170
+ For `h_lines`, `y` is a p-value (here `1e-20`, drawn at 20 on the -log10 axis).
171
+
172
+ ```python
173
+ (fig, ax) = ev.plot_volcano(df, y_thr=10**(-6), title="airway",
174
+ subtitle="custom thresholds and extra lines", x_thr=1,
175
+ h_lines={"y": 10**(-20), "linewidth":5, "color":"red", "linestyle" :"-"},
176
+ v_lines = [{"x": 2, "color":"pink"},
177
+ {"x": -3, "linestyle" : "dotted", "color": "darkgreen"}])
178
+ plt.show()
179
+ ```
180
+
181
+ ![custom lines](data/figures/custom_lines.png)
182
+
183
+ <a id="default-colours-and-marker"></a>
184
+
185
+ #### Default colours and marker
186
+
187
+ Every gene gets one of six colours from the two thresholds (p = adjusted p-value, lfc = log2 fold change):
188
+
189
+ | Parameter | Genes | Default |
190
+ |---|---|---|
191
+ | `color_up_sig` | p ≤ `y_thr` and lfc ≥ `x_thr` (legend: "Overexpressed") | `"#D7191C"` |
192
+ | `color_down_sig` | p ≤ `y_thr` and lfc ≤ -`x_thr` (legend: "Underexpressed") | `"#2C7BB6"` |
193
+ | `color_sig` | p ≤ `y_thr` but \|lfc\| < `x_thr` | `"darkgrey"` |
194
+ | `color_up` | p > `y_thr` but lfc ≥ `x_thr` | `"#FDAE61"` |
195
+ | `color_down` | p > `y_thr` but lfc ≤ -`x_thr` | `"#ABD9E9"` |
196
+ | `color_ns` | neither threshold | `"lightgrey"` |
197
+
198
+ Colours can be any matplotlib colour: a name (`"purple"`), a hex code (`"#762A83"`) or an RGB tuple.
199
+ `marker`, `size` and `alpha` change the shape, size and transparency of every point.
200
+
201
+ ```python
202
+ (fig, ax) = ev.plot_volcano(df, y_thr=1e-6, title="airway", subtitle="custom colours and marker",
203
+ color_up_sig="#762A83", color_down_sig="#1B7837",
204
+ color_up="#C2A5CF", color_down="#ACD39E",
205
+ color_sig="#878787", color_ns="#E0E0E0",
206
+ marker="^", size=60, alpha=0.8)
207
+ plt.show()
208
+ ```
209
+
210
+ ![custom colours](data/figures/custom_colours.png)
211
+
212
+ <a id="how-highlights-work"></a>
213
+
214
+ #### How highlights work
215
+
216
+ `highlights` is a **list of pairs**. Each pair says *which genes* and *how to draw them*:
217
+
218
+ ```python
219
+ highlights=[
220
+ (which_genes, how_to_draw),
221
+ (which_genes, how_to_draw),
222
+ ]
223
+ ```
224
+
225
+ For example, "draw FKBP5 and PER1 in red, bigger":
226
+
227
+ ```python
228
+ highlights=[ (["FKBP5", "PER1"], {"color": "red", "size": 200}) ]
229
+ # └─ which genes ──┘ └──────── how to draw ───────┘
230
+ ```
231
+
232
+ Three rules to remember:
233
+
234
+ 1. **Pairs are applied in order, and the last one wins.** If a gene is matched by two pairs, the later pair's style is used
235
+ (only for the options it sets; the rest are kept from earlier pairs).
236
+ 2. **Highlighted genes are drawn on top** of all other points, so they are never hidden.
237
+ 3. **You only change what you write.** Anything you don't set keeps its default (colour, size, transparency, ...).
238
+
239
+ ##### Which genes: three ways to select
240
+
241
+ | You write | Meaning | Example |
242
+ |---|---|---|
243
+ | a list of names | these genes | `["FKBP5", "PER1"]` |
244
+ | a rule: `lambda d: ...` | every gene for which the rule is true | `lambda d: d["baseMean"] < 100` |
245
+ | a True/False column | the genes marked True | `df["padj"] < 1e-10` |
246
+
247
+ - **Names** are looked up in the index of your table, or in `label_column` if you set it
248
+ (e.g. `label_column="gene_name"` to use symbols while your index holds Ensembl IDs).
249
+ Even a single gene goes in a list: `["FKBP5"]`, not `"FKBP5"`.
250
+ - **A rule** reads as: *"given the table `d`, keep the rows where ..."*. `d` is your table (rows with missing values removed),
251
+ so you can use any of its columns. Combine conditions with `&` (and), `|` (or), `~` (not), with each condition in parentheses:
252
+ `lambda d: (d["baseMean"] > 1000) & (d["log2FoldChange"] > 2)`.
253
+ For text, use pandas string methods: `lambda d: d.index.str.startswith("COL")`.
254
+
255
+ **Tip: check a rule before plotting.** A rule is just a function, so you can call it on your table
256
+ and count how many genes it selects:
257
+
258
+ ```python
259
+ rule = lambda d: (d["baseMean"] > 1000) & (d["padj"] < 1e-30)
260
+ print(rule(df).sum(), "genes selected")
261
+ df[rule(df)].head()
262
+ ```
263
+
264
+ Output:
265
+
266
+ ```text
267
+ 79 genes selected
268
+ ```
269
+
270
+ <a id="the-pattern-options-passed-to-matplotlib"></a>
271
+
272
+ #### The `{...}` pattern: options passed to matplotlib
273
+
274
+ Many options in easy_volcano are a **dictionary** (`{"name": value, ...}`), for example the *how to draw* part of a highlight,
275
+ `label_format`, `legend_kwargs` or each line in `h_lines`. A dictionary is just a bundle of named options.
276
+ easy_volcano hands it to the matplotlib function that draws that element, exactly as if you had typed the options yourself:
277
+
278
+ ```python
279
+ {"color": "red", "marker": "D", "edgecolors": "black"}
280
+ # is passed on as
281
+ ax.scatter(..., color="red", marker="D", edgecolors="black")
282
+ ```
283
+
284
+ This is why the possibilities are not limited to what easy_volcano lists: **any option the matplotlib function accepts works**.
285
+ When you want something new, look up the matplotlib function in the table below, find the option, and put it in the dictionary.
286
+
287
+ | Option in easy_volcano | Passed to matplotlib's | Useful keys (examples) |
288
+ |---|---|---|
289
+ | highlight style `(genes, {...})` | [`ax.scatter`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.scatter.html) | `color`, `size`, `alpha`, `marker`, `edgecolors`, `linewidths`, `zorder` |
290
+ | any extra keyword, e.g. `plot_volcano(df, edgecolors="none")` | `ax.scatter`, for every point | same as above |
291
+ | `label_format`, `label_genes_format`, `label_gene={...}` | [`ax.text`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.text.html) | `fontsize`, `fontweight`, `fontstyle`, `color` |
292
+ | `legend_kwargs` | [`ax.legend`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html) | `fontsize`, `frameon`, `title`, `ncols` |
293
+ | each line in `h_lines` / `v_lines` | [`ax.axhline` / `ax.axvline`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axhline.html) | `color`, `linestyle`, `linewidth`, `alpha` |
294
+
295
+ A few things easy_volcano adds on top:
296
+
297
+ - **Short names** in highlight styles: `size` means matplotlib's `s`, `color` means `c`, and `a` means `alpha`.
298
+ Use one form or the other, not both.
299
+ - **Extra keys** in highlight styles, handled by easy_volcano and not passed to matplotlib:
300
+ - `"label": "my genes"` adds the group to the legend,
301
+ - `"label_gene": True` writes the gene names on the plot; a dictionary (`{"fontweight": "bold"}`) also styles those names, like `label_format`.
302
+ - **Position keys are reserved**: in text formats, `x`, `y`, `s`, `position` and `text` are set by easy_volcano;
303
+ in `h_lines`/`v_lines`, `y`/`x` is the position (for `h_lines`, `y` is a p-value).
304
+
305
+ <a id="custom-colours-with-highlights"></a>
306
+
307
+ #### Custom colours with highlights
308
+
309
+ Select genes with a rule (a `lambda` on the table) or directly with a list of index names.
310
+ - Adding a `label` key adds the group to the legend.
311
+ - Setting `label_gene` adds the gene names to the plot.
312
+
313
+ Here shows that ribosomal protein gene are not DE
314
+
315
+ ```python
316
+ (fig, ax) = ev.plot_volcano(df, y_thr=10**(-6), width=6, title="airway", subtitle="ribosomal genes and two targets", legend_loc='bottom',
317
+ highlights= [(lambda d: d.index.str.startswith("RPL"),
318
+ {"color": "purple", "size": 80, "label": 'ribosomal gene'}),
319
+ (["GPX3", "STEAP2"] , {"color": "green", "label_gene": "True", "label": 'target' })
320
+ ]
321
+ )
322
+ plt.show()
323
+ ```
324
+
325
+ ![highlights](data/figures/highlights.png)
326
+
327
+ <a id="highlight-low-expression-genes"></a>
328
+
329
+ #### Highlight low expression genes
330
+
331
+ A rule can use any column of the table, here `baseMean`.
332
+
333
+ One could do the opposite and fade/ hide those.
334
+
335
+ ```python
336
+ (fig, ax) = ev.plot_volcano(df, y_thr=10**(-6), width=6, title="airway", subtitle="highlight low expression genes", legend_loc='bottom',
337
+ highlights= [(lambda d: d["baseMean"] < 100, {"alpha": 1, "color":"black", "label": "low expression" })]
338
+ )
339
+ plt.show()
340
+ ```
341
+
342
+ ![low expression](data/figures/low_expression.png)
343
+
344
+ <a id="spotlight"></a>
345
+
346
+ #### Spotlight
347
+
348
+ `no_default=True` turns off the default colouring, so only your genes stand out.
349
+
350
+ ```python
351
+ (fig, ax) = ev.plot_volcano(df, y_thr=10**(-6), width=6, title="airway", subtitle="spotlight",
352
+ no_default=True, label_top=None,
353
+ highlights= [(["GPX3", "STEAP2"] , {"color": "green", "label_gene": "True", "label": 'target' })]
354
+ )
355
+ plt.show()
356
+ ```
357
+
358
+ ![spotlight](data/figures/spotlight.png)
359
+
360
+ <a id="going-further"></a>
361
+
362
+ ### Going further
363
+
364
+ <a id="several-panels-and-clipping-p-values"></a>
365
+
366
+ #### Several panels and clipping p-values
367
+
368
+ - Pass `ax=` to draw into an existing figure, here two panels side by side.
369
+ - `clip_pval` (right) avoids a squashed plot when some p-values are extremely small or zero.
370
+
371
+ ```python
372
+ fig, axes = plt.subplots(ncols=2)
373
+ (fig, ax) = ev.plot_volcano(df, ax=axes[0], y_thr=10**(-6), width=6, title="airway", subtitle="without clipping",
374
+ no_default=True, label_top=None, font_size_text_summary=12,
375
+ highlights= [(["GPX3", "STEAP2"] , {"color": "green", "label_gene": "True", "label": 'target' })]
376
+ )
377
+ (fig, ax) = ev.plot_volcano(df, ax=axes[1], y_thr=10**(-6), width=6, title="airway", subtitle="clip_pval=1e-50",
378
+ no_default=True, label_top=None, clip_pval=10**(-50),font_size_text_summary=12,
379
+ highlights= [(["GPX3", "STEAP2"] , {"color": "green", "label_gene": "True", "label": 'target' })]
380
+ )
381
+ plt.show()
382
+ ```
383
+
384
+ ![clip pval panels](data/figures/clip_pval_panels.png)
385
+
386
+ <a id="master-example"></a>
387
+
388
+ #### Master example
389
+
390
+ Airway cells were treated with dexamethasone, a glucocorticoid. In one call:
391
+ - lowly expressed genes are faded (a rule on `baseMean`),
392
+ - collagens are picked by a rule on the gene name,
393
+ - canonical glucocorticoid targets are given as a plain list, drawn bigger with an outline, and labelled in bold,
394
+ - title, subtitle and legend are stacked on top without overlapping.
395
+
396
+ Highlights are applied in order: a gene matched by several layers keeps the last one.
397
+
398
+ ```python
399
+ gc_targets = ["FKBP5", "TSC22D3", "PER1", "KLF15", "ZBTB16",
400
+ "DUSP1", "CRISPLD2", "KLF9", "ERRFI1"]
401
+
402
+ fig, ax = ev.plot_volcano(
403
+ df, y_thr=1e-6, label_top=None, label_avoid_self=True,
404
+ title="Airway: dexamethasone",
405
+ subtitle="glucocorticoid targets and collagens",
406
+ legend_loc="top", legend_nrows=2,
407
+ highlights=[
408
+ # 1. fade lowly expressed genes
409
+ (lambda d: d["baseMean"] < 50, {"alpha": 0.1}),
410
+ # 2. a gene family picked by a rule on the index
411
+ (lambda d: d.index.str.startswith("COL"),
412
+ {"color": "#1b9e77", "size": 60, "label": "collagens"}),
413
+ # 3. a hand-picked list, outlined and labelled in bold
414
+ (gc_targets,
415
+ {"color": "#7b3294", "size": 250, "edgecolors": "black", "linewidths": 1,
416
+ "label": "glucocorticoid targets", "label_gene": {"fontweight": "bold"}}),
417
+ ])
418
+ plt.show()
419
+ ```
420
+
421
+ ![hero](data/figures/hero.png)
422
+
423
+ <a id="label-the-genes-you-care-about"></a>
424
+
425
+ #### Label the genes you care about
426
+
427
+ `label_top` labels the most significant genes on each side; `label_genes` adds your own.
428
+ `label_genes_format` styles only your genes (any matplotlib text option), and
429
+ `label_genes_line` draws a line from a label to its point when the label had to move.
430
+
431
+ ```python
432
+ fig, ax = ev.plot_volcano(
433
+ df, y_thr=1e-6, label_top=3,
434
+ label_genes=["FKBP5", "KLF15", "PER1", "CXCL12"],
435
+ label_genes_format={"fontweight": "bold", "color": "#7b3294"},
436
+ label_genes_line=True, label_min_arrow_len=5,
437
+ subtitle="top 3 per side + your genes, styled")
438
+ plt.show()
439
+ ```
440
+
441
+ ![label genes](data/figures/label_genes.png)
442
+
443
+ <a id="highlight-with-a-rule-over-any-columns"></a>
444
+
445
+ #### Highlight with a rule over any columns
446
+
447
+ A selector can be a function of the table: here, highly expressed **and** very significant genes.
448
+ The style dict accepts any `ax.scatter` argument (`marker`, `edgecolors`, `linewidths`, ...).
449
+
450
+ ```python
451
+ fig, ax = ev.plot_volcano(
452
+ df, y_thr=1e-6, label_top=None,
453
+ subtitle="rule over several columns", legend_nrows=2,
454
+ highlights=[
455
+ (lambda d: (d["baseMean"] > 1000) & (d["padj"] < 1e-30),
456
+ {"marker": "D", "size": 50, "color": "gold", "edgecolors": "black",
457
+ "label": "baseMean > 1000 and padj < 1e-30"}),
458
+ ])
459
+ plt.show()
460
+ ```
461
+
462
+ ![rule highlight](data/figures/rule_highlight.png)
463
+
464
+ <a id="layered-highlights-later-wins"></a>
465
+
466
+ #### Layered highlights: later wins
467
+
468
+ All collagens are green; collagens that also change more than 2-fold are then restyled by a second layer
469
+ (darker, bigger, outlined and labelled).
470
+
471
+ ```python
472
+ fig, ax = ev.plot_volcano(
473
+ df, y_thr=1e-6, label_top=None,
474
+ subtitle="layered highlights: later wins", legend_nrows=2,
475
+ highlights=[
476
+ (lambda d: d.index.str.startswith("COL"),
477
+ {"color": "#1b9e77", "size": 60, "label": "collagens"}),
478
+ (lambda d: d.index.str.startswith("COL") & (d["log2FoldChange"].abs() > 1),
479
+ {"color": "#0b5d44", "size": 200, "edgecolors": "black",
480
+ "label": "collagens |LFC| > 1", "label_gene": True}),
481
+ ])
482
+ plt.show()
483
+ ```
484
+
485
+ ![layers](data/figures/layers.png)
486
+
487
+ <a id="keep-going-with-matplotlib"></a>
488
+
489
+ #### Keep going with matplotlib
490
+
491
+ `plot_volcano` returns `(fig, ax)`, so anything matplotlib can do still works afterwards:
492
+ here a shaded region and an annotation with an arrow.
493
+
494
+ ```python
495
+ fig, ax = ev.plot_volcano(df, y_thr=1e-6, label_top=None,
496
+ subtitle="returns (fig, ax): keep going with matplotlib")
497
+ xlim = ax.get_xlim()
498
+ ax.axvspan(2, xlim[1], color="#D7191C", alpha=0.08, zorder=0) # shade a region
499
+ ax.set_xlim(xlim) # keep the original limits
500
+ gene = "ZBTB16"
501
+ xy = (df.loc[gene, "log2FoldChange"], -np.log10(df.loc[gene, "padj"]))
502
+ ax.annotate(f"{gene}\nstrongest induction", xy=xy, xytext=(xy[0] - 2.5, xy[1] + 40),
503
+ arrowprops=dict(arrowstyle="->"), fontsize=11)
504
+ plt.show()
505
+ ```
506
+
507
+ ![matplotlib after](data/figures/matplotlib_after.png)
508
+
509
+ <a id="export-for-illustrator"></a>
510
+
511
+ #### Export for Illustrator
512
+
513
+ Text is saved as editable text in PDF. With `rasterize=True` the points become an image while
514
+ text, axes and lines stay vector, so the file stays small and still opens quickly in Illustrator.
515
+
516
+ ```python
517
+ for raster in (False, True):
518
+ path = Path(f"volcano_rasterize_{raster}.pdf")
519
+ fig, ax = ev.plot_volcano(df, y_thr=1e-6, rasterize=raster, savefig=path)
520
+ plt.close(fig)
521
+ print(f"rasterize={raster}: {path.stat().st_size / 1e3:.0f} kB")
522
+ ```
523
+
524
+ Output:
525
+
526
+ ```text
527
+ rasterize=False: 2625 kB
528
+ rasterize=True: 57 kB
529
+ ```
530
+
531
+ <!-- examples:end -->
532
+
533
+ ## Not supported yet
534
+
535
+ - density plots
536
+ - continuous colour scales
537
+ - boxed labels
538
+
539
+ <a id="all-options"></a>
540
+
541
+ ## All options
542
+
543
+ <!-- options:start -->
544
+
545
+ All parameters of `plot_volcano`, from its docstring (also available with `help(ev.plot_volcano)`):
546
+
547
+ ```text
548
+ Draw a volcano plot from a differential-expression results table.
549
+
550
+ Each gene is a point: log2 fold change on the x-axis, -log10 of the adjusted
551
+ p-value on the y-axis. Points are first coloured by significance category
552
+ (see "Default colours"), then any `highlights` are drawn on top of them.
553
+ Rows with a missing value in the `x` or `y` column are dropped.
554
+
555
+ Example
556
+ -------
557
+ >>> fig, ax = plot_volcano(df, y_thr=1e-6, label_top=5,
558
+ ... highlights=[(["FKBP5", "PER1"], {"color": "purple", "size": 200, "label": "my genes"})])
559
+
560
+ Parameters
561
+ ----------
562
+ df : pandas.DataFrame
563
+ Results table with one row per gene (e.g. DESeq2, edgeR or limma output).
564
+ Gene names are read from the index, or from `label_column`.
565
+
566
+ Data and thresholds
567
+ ~~~~~~~~~~~~~~~~~~~
568
+ x : str, default "log2FoldChange"
569
+ Column with the log2 fold change (x-axis). edgeR and limma: "logFC".
570
+ y : str, default "padj"
571
+ Column with the adjusted p-value, plotted as -log10 (y-axis).
572
+ edgeR: "FDR"; limma: "adj.P.Val".
573
+ x_thr : float or None, default 1
574
+ Absolute log2 fold-change threshold. Used for the default colours, the
575
+ vertical threshold lines, the summary and `label_top`.
576
+ y_thr : float or None, default 0.01
577
+ Adjusted p-value threshold (a p-value, not its -log10). Used for the
578
+ default colours, the horizontal threshold line and the summary.
579
+ If `x_thr` or `y_thr` is None, the default colouring is turned off.
580
+ clip_pval : float or None, default None
581
+ If set (strictly between 0 and 1), every p-value below it is raised to it,
582
+ so a few extreme genes do not squash the rest of the plot.
583
+ Takes priority over `pval_floor`.
584
+ pval_floor : bool, default False
585
+ Where p-values of exactly 0 are drawn (log10(0) is undefined).
586
+ False: at the smallest non-zero p-value of the table.
587
+ True: at the smallest positive float (about 1e-308), i.e. far above the rest.
588
+
589
+ Default colours
590
+ ~~~~~~~~~~~~~~~
591
+ Each gene falls in one category, from its p-value (p, column `y`) and its
592
+ log2 fold change (lfc, column `x`):
593
+
594
+ color_up_sig : str, default "#D7191C"
595
+ p <= y_thr and lfc >= x_thr. Shown in the legend as "Overexpressed".
596
+ color_down_sig : str, default "#2C7BB6"
597
+ p <= y_thr and lfc <= -x_thr. Shown in the legend as "Underexpressed".
598
+ color_sig : str, default "darkgrey"
599
+ p <= y_thr but |lfc| < x_thr.
600
+ color_up : str, default "#FDAE61"
601
+ p > y_thr but lfc >= x_thr.
602
+ color_down : str, default "#ABD9E9"
603
+ p > y_thr but lfc <= -x_thr.
604
+ color_ns : str, default "lightgrey"
605
+ p > y_thr and |lfc| < x_thr.
606
+ no_default : bool, default False
607
+ Turn the default colouring off: every point gets `color_base`.
608
+ Combine with `highlights` for a "spotlight" plot.
609
+
610
+ Points
611
+ ~~~~~~
612
+ color_base : str, default "grey"
613
+ Colour of points that no category or highlight colours.
614
+ size : float, default 100
615
+ Point size (matplotlib's `s`, an area in points squared).
616
+ marker : str, default "."
617
+ Point shape: any matplotlib marker ("o", "D", "^", ...).
618
+ alpha : float, default 0.55
619
+ Point transparency, from 0 (invisible) to 1 (opaque).
620
+ rasterize : bool, default False
621
+ When saving to PDF or SVG, draw the points as an image while text, axes
622
+ and lines stay vector: much smaller files that open quickly in
623
+ Illustrator. Overrides any "rasterized" set in `highlights`.
624
+ **scatter_kwargs
625
+ Any other keyword is passed to matplotlib's `ax.scatter` for every point,
626
+ e.g. edgecolors="none" or linewidths=0.
627
+
628
+ Highlights
629
+ ~~~~~~~~~~
630
+ highlights : list of (selector, style) pairs, default None
631
+ Restyle chosen genes. Highlighted genes are drawn on top of all other
632
+ points. Pairs are applied in order: when a gene matches several pairs,
633
+ the later pair wins for the options it sets.
634
+
635
+ selector (which genes), one of:
636
+ - a list, tuple or set of names, matched against the index, or against
637
+ `label_column` if set. A single gene is still a list: ["FKBP5"].
638
+ - a function of the table, e.g. lambda d: d["baseMean"] < 100.
639
+ `d` is `df` without the NA rows, so any column can be used.
640
+ - a boolean pandas Series indexed like `df`.
641
+
642
+ style (how to draw them): a dict of `ax.scatter` options ("color", "size",
643
+ "alpha", "marker", "edgecolors", "linewidths", "zorder", ...). "color",
644
+ "size" and "a" are short for matplotlib's "c", "s" and "alpha".
645
+ Two extra keys:
646
+ - "label": str, adds the group to the legend.
647
+ - "label_gene": True to write the gene names on the plot, or a dict of
648
+ text options (like `label_format`) to also style those names.
649
+
650
+ Example: [(lambda d: d.index.str.startswith("COL"),
651
+ {"color": "green", "size": 150, "label": "collagens"})]
652
+
653
+ Gene labels
654
+ ~~~~~~~~~~~
655
+ Labels are positioned with adjustText to limit overlaps. Each gene is labelled
656
+ once, with priority: highlight "label_gene" > `label_genes` > `label_top`.
657
+
658
+ label_top : int or None, default 5
659
+ Label the N genes with the smallest p-value on each side (lfc > x_thr and
660
+ lfc < -x_thr), so up to 2 * N labels. None: no automatic labels.
661
+ label_genes : str or list of str, default None
662
+ Genes to label, matched against the index or `label_column`.
663
+ Names that are not found are reported in a warning.
664
+ label_column : str or None, default None
665
+ Column holding the gene names to use, in labels and in name selectors,
666
+ instead of the index (e.g. "gene_name" when the index holds Ensembl IDs).
667
+ label_format : dict, default {"fontsize": 10, "fontstyle": "normal", "ha": "center", "va": "center"}
668
+ Text options for all labels (matplotlib's `ax.text`), merged on the default.
669
+ The keys "x", "y", "s", "position" and "text" are reserved.
670
+ label_genes_format : dict or None, default None
671
+ Text options applied on top of `label_format` to the `label_genes` only,
672
+ e.g. {"fontweight": "bold", "color": "purple"}.
673
+ label_genes_line : bool, default False
674
+ Draw a line between each label and its point when the label was moved
675
+ further than `label_min_arrow_len` (applies to all labels).
676
+ label_min_arrow_len : float, default 100
677
+ Shortest line drawn by `label_genes_line`, in pixels. With the default,
678
+ most lines are too short to be drawn: use about 5 to see them.
679
+ label_avoid_self : bool, default False
680
+ Also push each label away from its own point.
681
+
682
+ Lines and grid
683
+ ~~~~~~~~~~~~~~
684
+ show_thresholds_line : bool, default True
685
+ Draw the threshold lines at `y_thr` and at -`x_thr` and +`x_thr`.
686
+ line_format_default : dict, default {"color": "black", "linestyle": "--"}
687
+ Style of the threshold lines (matplotlib's `ax.axhline` / `ax.axvline`
688
+ options), merged on the default.
689
+ h_lines : dict or list of dict, default None
690
+ Extra horizontal lines. Each dict needs "y", a p-value (drawn at
691
+ -log10(y)), plus any line option, e.g. {"y": 1e-20, "color": "red"}.
692
+ Black dashed by default.
693
+ v_lines : dict or list of dict, default None
694
+ Extra vertical lines. Each dict needs "x", a log2 fold change, plus any
695
+ line option, e.g. {"x": 2, "linestyle": ":"}. Black dashed by default.
696
+ display_grid : bool, default True
697
+ Draw major and minor grid lines.
698
+
699
+ Title, legend and summary
700
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
701
+ The elements around the plot are stacked so they never overlap. Above the
702
+ plot, from the axes up: legend (if legend_loc="top"), subtitle, title. Below
703
+ the plot, from the x-axis label down: legend (if legend_loc="bottom"),
704
+ summary. Paddings are gaps in points, so they do not depend on figure size.
705
+
706
+ title : str, default ""
707
+ Plot title. Not drawn if empty.
708
+ title_fontsize : float, default 28
709
+ title_pad : float, default 15
710
+ Gap (points) between the title and the element below it.
711
+ subtitle : str, default ""
712
+ Text between the title and the plot. Not drawn if empty.
713
+ subtitle_fontsize : float, default 18
714
+ subtitle_pad : float, default 15
715
+ Gap (points) between the subtitle and the element below it.
716
+ xlabel : str, default "$Log_{2}$ fold change"
717
+ ylabel : str, default "$-Log_{10}$ adj.P"
718
+ Axis labels. Text between $ signs is rendered as math.
719
+ show_legend : bool, default True
720
+ Draw the legend. False is the same as legend_loc=None.
721
+ legend_loc : {"bottom", "top", "right"} or None, default "bottom"
722
+ Legend position. None: no legend. Entries are "Overexpressed",
723
+ "Underexpressed" and every highlight with a "label"; with no entries,
724
+ no legend is drawn.
725
+ legend_nrows : int or None, default None
726
+ Number of legend rows. None: one row for "top" and "bottom", one column
727
+ for "right". An explicit "ncols" in `legend_kwargs` wins.
728
+ legend_kwargs : dict or None, default None
729
+ Options passed to matplotlib's `ax.legend`, applied on top of the preset,
730
+ e.g. {"fontsize": 12, "frameon": False, "title": "groups"}.
731
+ padding_legend : float, default 15
732
+ Gap (points) between the legend and the plot ("top") or the x-axis
733
+ label ("bottom"). Not used for "right".
734
+ show_text_summary : bool, default True
735
+ Write "up N; down N; ns N" under the plot: genes with p <= y_thr and
736
+ lfc >= x_thr, genes with p <= y_thr and lfc <= -x_thr, and all others.
737
+ Needs both `x_thr` and `y_thr`.
738
+ font_size_text_summary : float, default 16
739
+ padding_text_summary : float, default 15
740
+ Gap (points) between the summary and the element above it.
741
+
742
+ Figure and output
743
+ ~~~~~~~~~~~~~~~~~
744
+ ax : matplotlib Axes or None, default None
745
+ Draw into this existing Axes, e.g. one panel of plt.subplots(); `width`
746
+ and `height` are then ignored. None: create a new figure.
747
+ width : float, default 6
748
+ Figure width in inches.
749
+ height : float, default 6
750
+ Figure height in inches.
751
+ Tick and axis-label font sizes follow the size of the plot.
752
+ color_bg : str, default "white"
753
+ Background colour of the plot area.
754
+ savefig : str or path, default None
755
+ Save the figure to this file (format from the extension: .png, .pdf,
756
+ .svg, ...), cropped to its content. Text stays editable in PDF files.
757
+
758
+ Returns
759
+ -------
760
+ fig, ax : matplotlib Figure and Axes
761
+ Keep customising them with matplotlib (annotations, shading, limits, ...).
762
+
763
+ Raises
764
+ ------
765
+ ValueError
766
+ If no row is left after dropping missing values, if no p-value is above 0
767
+ (is `y` already -log10 transformed?), if `clip_pval` is not between 0 and 1,
768
+ or if `legend_loc` is not one of the presets.
769
+ ```
770
+
771
+ <!-- options:end -->