Plotting
This module contains functions for plotting protein data.
Functions:
Name | Description |
---|---|
plot_significance |
Plot significance bars on a given axis. |
plot_cv |
Generate a violin plot for the coefficient of variation (CV) of different cases. |
plot_abundance |
Plot the abundance of proteins across different cases. |
plot_pca |
Plot a PCA of the protein data. |
plot_umap |
Plot a UMAP of the protein data. |
plot_pca_scree |
Plot a scree plot of the PCA. |
plot_heatmap |
Plot a heatmap of protein abundance data. |
plot_volcano |
Plot a volcano plot of protein data. |
plot_rankquant |
Plot a rank-quantile plot of protein data. |
plot_abundance_2D |
Plot the abundance of proteins across different cases in 2D. |
mark_rankquant |
Mark the rank-quantile plot with specific proteins. |
plot_raincloud |
Plot a raincloud plot of protein data. |
mark_raincloud |
Mark the raincloud plot with specific proteins. |
Todo
- For future implementation.
get_color(resource_type, n=None)
Generate a list of colors, a colormap, or a palette from package defaults.
Parameters: - resource_type (str): The type of resource to generate. Options are 'colors', 'cmap', and 'palette'. If 'show', displays all 7 colors. - n (int, optional): The number of colors or colormaps to generate. Required for 'colors' and 'cmap'.
Returns: - list of str: If resource_type is 'colors', a list of hex color strings. Repeats colors if n > 7. - list of matplotlib.colors.LinearSegmentedColormap: If resource_type is 'cmap' - seaborn.color_palette: If resource_type is 'palette' - None: If resource_type is 'show', displays the colors and colormaps.
Example:
colors = get_color('colors', 5) cmap = get_color('cmap') palette = get_color('palette')
Source code in src/scviz/plotting.py
mark_volcano(ax, volcano_df, label, label_color='black', label_type='Gene', s=10, alpha=1, show_names=True, fontsize=8)
Mark the volcano plot with specific proteins.
Parameters: ax (matplotlib.axes.Axes): The axes on which to plot. volcano_df (pandas.DataFrame): volcano_df data returned from get_protein_DE() or plot_volcano(). label (list): The genes to highlight. Can be list of list of genes to highlight for each case. color (str, optional): The color of the markers. Defaults to 'black'. Can be list of colors for each case. s (float, optional): The size of the markers. Defaults to 10. alpha (float, optional): The transparency of the markers. Defaults to 1. show_names (bool, optional): Whether to show the gene names. Defaults to True.
Returns: ax (matplotlib.axes.Axes): The axes with the plot.
Example:
fig, ax = plt.subplots(1,1) ax, volcano_df = scplt.plot_volcano(ax, data, cases, log2fc=0.5, pval=0.05, alpha=0.5, fontsize=6, label=[1,2,3]); ax = scplt.mark_volcano(ax, data, cases, label=['P11247','O35639','F6ZDS4'], color='red', s=10, alpha=1, show_names=True)
Source code in src/scviz/plotting.py
plot_abundance(ax, pdata, namelist=None, layer='X', on='protein', classes=None, return_df=False, order=None, palette=None, log=True, facet=None, height=4, aspect=0.5, plot_points=True, x_label='gene', kind='auto', **kwargs)
Plot abundance of proteins/peptides using violin + box (inner="box") + strip.
Parameters: ax (matplotlib.axes.Axes): Axis to plot on (ignored if facet is used). pdata (pAnnData): Your pAnnData object. namelist (list of str): Accessions or gene names to plot. layer (str): Data layer name. on (str): 'protein' or 'peptide'. classes (str or list): obs column(s) to group by (used for color). return_df (bool): If True, return DataFrame with replicate + summary values. order (list): Custom order of classes. palette (list or dict): Color palette. log (bool): Plot log2(abundance). facet (str or None): obs column to facet by. height, aspect (float): For facet layout. plot_points (bool): Show stripplot of individual samples. x_label (str): Label x-axis as 'gene' or 'accession'. kind (str): 'auto' (default), 'violin', or 'bar'. If 'auto', switches to barplot if all groups ≤ 3 samples. **kwargs: Extra args passed to violinplot or barplot depending on kind.
Returns: matplotlib.Axes or sns.FacetGrid or pd.DataFrame
Source code in src/scviz/plotting.py
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
|
plot_cv(ax, pdata, classes=None, layer='X', on='protein', order=None, return_df=False, **kwargs)
Generate a box and whisker plot for the coefficient of variation (CV) of different cases.
Parameters: ax (matplotlib.axes.Axes): The axis on which to plot. data (pandas.DataFrame): The data to plot. It should contain columns for each case, with each column containing the CV values for that case. cases (list of list of str): A list of cases to plot. Each case is a list of strings that are used to select the columns from the data. color (list of str, optional): A list of colors for the box plots of each case. If not provided, all boxes will be blue.
Returns: matplotlib.axes.Axes: The axis with the plotted data.
Example:
Source code in src/scviz/plotting.py
plot_enrichment_svg(*args, **kwargs)
Plot STRING enrichment results as an SVG figure.
NOTE
This function is implemented in enrichment.py
, not plotting.py
.
See Also
scviz.enrichment.plot_enrichment_svg
Source code in src/scviz/plotting.py
plot_heatmap(ax, heatmap_data, cmap=cm.get_cmap('seismic'), norm_values=[4, 5.5, 7], linewidth=0.5, annotate=True, square=False, cbar_kws={'label': 'Abundance (AU)'})
Plot annotated heatmap of protein abundance data.
Parameters:
ax (matplotlib.axes.Axes): The axes on which to plot the heatmap.
heatmap_data (pandas.DataFrame): The data to plot.
cmap (matplotlib.colors.Colormap): The colormap to use for the heatmap.
norm_values (list): The low, mid, and high values used to set colorbar scale. Can be assymetric.
linewidth (float): Plot linewidth.
annotate (bool): Annotate each heatmap entry with numerical value. True by default.
square (bool): Make heatmap square. False by default.
cbar_kws (dict): Pass-through keyword arguments for the colorbar. See matplotlib.figure.Figure.colorbar()
for more information.
Returns: ax (matplotlib.axes.Axes): The axes with the plotted heatmap.
Source code in src/scviz/plotting.py
plot_pca(ax, pdata, classes=None, layer='X', on='protein', cmap='default', s=20, alpha=0.8, plot_pc=[1, 2], pca_params=None, force=False, show_labels=False, label_column=None, add_ellipses=False, ellipse_kwargs=None)
Plot PCA scatter plot for classes, protein or peptide abundance.
Parameters: - ax (matplotlib.axes.Axes): The axis to plot on (must be 3D if plotting 3 PCs). - pdata (scviz.pAnnData): The pAnnData object with .prot, .pep, and .summary. - classes (str or list of str or None): - None: plot in grey - str: an obs column (e.g. 'treatment') or a protein/gene (e.g. 'UBE4B') - list of str: combine multiple obs columns (e.g. ['cellline', 'treatment']) - layer (str): The layer to extract from adata (default: "X"). - on (str): 'protein' or 'peptide' (default: 'protein'). - cmap (str, list, or colormap): - 'default': use get_color() scheme - list of colors: used for obs classes - colormap name or object: used for continuous abundance coloring - s (float): Scatter dot size (default: 20). - alpha (float): Dot opacity (default: 0.8). - plot_pc (list): PCs to plot (e.g. [1,2] or [1,2,3]). - pca_params (dict): Params for PCA, passed to sklearn PCA. - force (bool): If True, re-calculate PCA even if it already exists. - show_labels (bool or list): - False: no labels - True: show all sample names - list: only label specified sample names (e.g. ['sample1.raw', 'sample2.raw']) - label_column (str or None): Optional column in pdata.summary to use as label source. - add_ellipses (bool): If True, overlay confidence ellipses per class (2D only). Note: Confidence ellipses are calculated from the group covariance matrix and represent a 95% confidence region under a bivariate Gaussian assumption. - ellipse_kwargs (dict): Optional kwargs to pass to ellipse patch.
Returns: - ax (matplotlib.axes.Axes): The plot axes. - pca (sklearn.decomposition.PCA): The fitted PCA object.
Examples:
plot_pca(ax, pdata) # plot in grey plot_pca(ax, pdata, classes='treatment') # color by categorical obs plot_pca(ax, pdata, classes=['cellline', 'treatment']) # combined label plot_pca(ax, pdata, classes='UBE4B') # color by protein expression plot_pca(ax, pdata, show_labels=True) # label each sample plot_pca(ax, pdata, show_labels=True, label_column='short_name') # use custom label plot_pca(ax, pdata, classes='treatment', add_ellipses=True) # add default ellipses plot_pca(ax, pdata, classes='treatment', add_ellipses=True, ellipse_kwargs={'alpha': 0.1, 'lw': 2})
Source code in src/scviz/plotting.py
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 |
|
plot_pca_scree(ax, pca)
Plot a scree plot of the PCA.
Parameters: ax (matplotlib.axes.Axes): The axes on which to plot the scree plot. pca (sklearn.decomposition.PCA or dict): The fitted PCA model, or a dict from .uns with keys: 'variance_ratio'.
Returns: ax (matplotlib.axes.Axes): The axes with the plotted scree plot.
Example:
import matplotlib.pyplot as plt import pandas as pd import numpy as np from scviz import plotting as scplt data = pd.read_excel('tests/data.xlsx', sheet_name='Proteins') cases = [['head'],['heart'],['tail']] fig, ax = plt.subplots(1,1) ax, pca = scplt.plot_pca(ax, data, cases, cmap='viridis', s=20, alpha=.8, plot_pc=[1,2]) ax = scplt.plot_pca_scree(ax, pca) scplt.plot_pca_scree(ax, data.prot.uns['pca'])
Source code in src/scviz/plotting.py
plot_rankquant(ax, pdata, classes=None, layer='X', on='protein', cmap=['Blues'], color=['blue'], order=None, s=20, alpha=0.2, calpha=1, exp_alpha=70, debug=False)
Plot rank abundance of proteins across different classes.
Parameters: ax (matplotlib.axes.Axes): The axis on which to plot. pdata (scviz.pAnnData): The input pdata object. classes (list of str): A list of classes to plot. If None, all .obs are combined into identifier classes. Default is None. layer (str, optional): The layer to use for the plot. Default is 'X'. on (str, optional): The data to use for the plot. Default is 'protein'. cmap (str, optional): The colormap to use for the scatter plot. Default is 'Blues'. color (list of str, optional): A list of colors for the scatter plots of each class. If not provided, all plots will be blue. order (list of str, optional): The order of the classes to plot. If not provided, the classes will be plotted in the order they appear in the data. s (float, optional): The marker size. Default is 20. alpha (float, optional): The marker transparency. Default is 0.2. calpha (float, optional): The marker transparency for distribution dots. Default is 1. append_var (bool, optional): If True, append the average and stdev values to the pdata.[on].var. Default is True. Needs to be True for mark_rankquant to work. exp_alpha (float, optional): The exponent for the pdf value based on average abundance. Default is 70.
Example:
colors = sns.color_palette("Blues", 4) cmaps = ['Blues', 'Reds', 'Greens', 'Oranges'] fig, ax = plt.subplots(figsize=(4,3)) ax = scplt.plot_rankquant(ax, pdata_filter, classes = 'size', order = ['sc', '5k','10k', '20k'], cmap = cmaps, color=colors, calpha = 1, alpha = 0.005)
Source code in src/scviz/plotting.py
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 |
|
plot_significance(ax, y, h, x1=0, x2=1, col='k', pval='n.s.', fontsize=12)
Plot significance bars on a given axis.
Parameters: ax (matplotlib.axes.Axes): The axis on which to plot the significance bars. y (float): The y-coordinate of the bars. h (float): The height of the bars. x1 (float): The x-coordinate of the first bar. x2 (float): The x-coordinate of the second bar. col (str): The color of the bars. pval (float or str): The p-value used to determine the significance level of the bars. If a float, it is compared against predefined thresholds to determine the significance level. If a string, it is directly used as the significance level. fontsize (int): The fontsize of the significance level text.
Returns: None
Source code in src/scviz/plotting.py
plot_umap(ax, pdata, color=None, layer='X', on='protein', cmap='default', s=20, alpha=0.8, umap_params={}, text_size=10, force=False)
This function plots the Uniform Manifold Approximation and Projection (UMAP) of the protein data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ax
|
Axes
|
The axes to plot on. |
required |
data
|
DataFrame
|
The protein data to plot. |
required |
color
|
str
|
The column in the data to color by. |
None
|
cmap
|
Colormap
|
The colormap to use for the plot. Defaults to 'viridis'. |
'default'
|
s
|
int
|
The size of the points in the plot. Defaults to 20. |
20
|
alpha
|
float
|
The transparency of the points in the plot. Defaults to 0.8. |
0.8
|
umap_params
|
dict
|
A dictionary of parameters to pass to the UMAP function. Possible keys are 'min_dist', 'n_components', 'metric', and 'random_state'. Defaults to an empty dictionary, in which case the default UMAP parameters are used. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
ax |
Axes
|
The axes with the plot. |
fit_umap |
UMAP
|
The fitted UMAP object. |
Raises:
Type | Description |
---|---|
AssertionError
|
If 'n_components' is 3 but the axes is not a 3D projection. |
Source code in src/scviz/plotting.py
plot_volcano(ax, pdata=None, classes=None, values=None, method='ttest', fold_change_mode='mean', label=5, label_type='Gene', color=None, alpha=0.5, pval=0.05, log2fc=1, linewidth=0.5, fontsize=8, no_marks=False, de_data=None, return_df=False, **kwargs)
Plot a volcano plot on the given axes. Calculates DE on pdata across the given class_type and values. Alternatively, can use pre-calculated DE data (see pdata.de() dataframe for example input).
Parameters: ax (matplotlib.axes.Axes): The axes on which to plot. pdata (scviz.pAnnData): The input pdata object. classes (str): The class type to use for the comparison. values (list or dict): The values to compare. Can be legacy list format or new dict format. method (str, optional): The method to use for the comparison. Defaults to 'ttest'. fold_change_mode : str Method for computing fold change. Options: - 'mean' : log2(mean(group1) / mean(group2)) - 'pairwise_median' : median of all pairwise log2 ratios label (int or list): The genes to highlight. If an int, the top and bottom n genes are shown. If a list, only those genes are shown. Can also accept list with 2 numbers to show top and bottom n genes [top, bottom]. If none, no labels will be plotted. label_type (str, optional): Label type. Currently only 'Gene' is recommended. color (dict, optional): A dictionary mapping significance to colors. Defaults to grey/red/blue. alpha (float, optional): Scatter dot transparency. Defaults to 0.5. pval (float, optional): The p-value threshold for significance. Defaults to 0.05. log2fc (float, optional): The log2 fold change threshold for significance. Defaults to 1. linewidth (float, optional): The linewidth for the threshold lines. Defaults to 0.5. fontsize (int, optional): Fontsize for gene labels. Defaults to 8. no_marks (bool, optional): If True, suppress volcano point coloring. All points are grey. de_data (pd.DataFrame): Optional pre-computed DE dataframe. Must contain 'log2fc', 'p_value', 'significance'. return_df (bool, optional): If True, return the dataframe used for plotting. **kwargs: Extra kwargs passed to matplotlib scatter plot.
Returns: matplotlib.axes.Axes or (ax, df)
Note:
Use the helper function add_volcano_legend(ax)
to add standard volcano legend handles.
Example:
ax, df = plot_volcano(ax, pdata, classes='cellline', values=['A', 'B']) add_volcano_legend(ax)
Source code in src/scviz/plotting.py
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 |
|
resolve_pca_colors(adata, classes, cmap, layer='X')
Resolve colors for PCA plot based on classes. Helper function for plot_pca. Returns: - color_mapped: array-like values to use for coloring - cmap_resolved: colormap (only for continuous coloring) - legend_elements: legend handles (only for categorical coloring)
Source code in src/scviz/plotting.py
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 |
|