Data Visualization with Matplotlib and Related Libraries in Bioinformatics

  • Data visualization is an essential part of bioinformatics because biological research generates large and complex datasets that are often difficult to interpret using numerical tables alone. Genomic sequences, gene-expression measurements, protein structures, genetic variants, evolutionary relationships, and biological networks can contain thousands or millions of observations. Visualization transforms these data into graphical representations that help researchers identify patterns, compare experimental groups, detect outliers, explore relationships, and communicate scientific findings.
  • Python provides a rich ecosystem of visualization libraries, including Matplotlib, Seaborn, Plotly, Bokeh, Altair, and specialized tools such as Scanpy for single-cell analysis and Biopython utilities for sequence-related visualization. Matplotlib is one of the most widely used libraries because it supports a broad range of static plots and offers detailed control over figure dimensions, axes, labels, legends, colors, and annotations. Other libraries build on or complement Matplotlib by simplifying statistical visualization, providing interactive graphics, or supporting specialized biological data.
  • Matplotlib is particularly useful for visualizing numerical data generated through NumPy, SciPy, and pandas. Its pyplot interface provides functions for creating line plots, scatter plots, bar charts, histograms, box plots, heatmaps, and many other graphics. Researchers can use these plots to explore gene-expression distributions, compare protein properties, examine sequencing quality, visualize model predictions, and summarize experimental measurements.
  • Matplotlib can be installed with Python’s package manager:
  • python -m pip install matplotlib numpy pandas seaborn
  • The library is commonly imported using the alias plt. NumPy and pandas are often used to prepare the data before visualization, while Seaborn provides higher-level statistical plotting functions.

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

import seaborn as sns

  • A line plot is useful when observations have a natural order, such as measurements collected over time, changes in gene expression during development, or the progress of a biological simulation. The horizontal axis generally represents time or another ordered variable, while the vertical axis represents the measurement of interest. Connecting points with lines helps reveal trends, fluctuations, and possible changes in behavior.
  • For example, gene-expression measurements collected at several time points can be visualized using a line plot.

import matplotlib.pyplot as plt

time = [0, 2, 4, 6, 8, 10]

expression = [5, 8, 14, 22, 19, 27]

plt.plot(time, expression, marker=”o”)

plt.xlabel(“Time (hours)”)

plt.ylabel(“Gene expression”)

plt.title(“Gene Expression Over Time”)

plt.grid(True, alpha=0.3)

plt.tight_layout()

plt.show()

  • This example displays an illustrative expression profile. The markers indicate individual observations, while the connecting line helps show the overall trend. In real experiments, researchers should distinguish raw measurements from normalized or transformed expression values and indicate whether points represent individual biological replicates, group means, or model estimates.
  • A scatter plot is useful for examining the relationship between two numerical variables. In bioinformatics, scatter plots can reveal associations between the expression levels of two genes, relationships between protein abundance and molecular weight, or differences between measured and predicted values. A scatter plot can also reveal outliers, nonlinear patterns, and clusters that may require further investigation.

import matplotlib.pyplot as plt

gene_a = [10, 15, 20, 25, 30, 35]

gene_b = [12, 18, 17, 28, 32, 38]

plt.scatter(gene_a, gene_b)

plt.xlabel(“Gene A expression”)

plt.ylabel(“Gene B expression”)

plt.title(“Relationship Between Two Genes”)

plt.tight_layout()

plt.show()

  • Each point represents one observation, such as a sample in which both genes were measured. A visible association does not necessarily indicate direct regulation or a causal relationship. Correlation coefficients, statistical models, experimental design, and potential confounding factors should be considered before drawing biological conclusions.
  • Bar charts are often used to compare quantities across discrete categories. For example, they can show the number of variants identified on different chromosomes, the abundance of microbial taxa, or the average measurement for several experimental groups. However, bar charts should be selected carefully when the underlying data contain many observations or substantial variability. Showing individual observations and uncertainty can be more informative than presenting group averages alone.

import matplotlib.pyplot as plt

conditions = [“Control”, “Treatment A”, “Treatment B”]

mean_expression = [12, 18, 25]

plt.bar(conditions, mean_expression)

plt.xlabel(“Experimental condition”)

plt.ylabel(“Mean expression”)

plt.title(“Comparison of Mean Gene Expression”)

plt.tight_layout()

plt.show()

  • This plot compares three illustrative group means. If these means are calculated from biological replicates, error bars or individual data points may be necessary to communicate variability. The figure should identify the error-bar definition, such as standard deviation, standard error, or a confidence interval. These quantities represent different concepts and should not be used interchangeably.
  • Histograms show the distribution of numerical observations by dividing values into intervals called bins. They are useful for examining gene-expression values, sequencing read lengths, protein molecular weights, genomic feature lengths, and variant quality scores. The shape of a histogram can suggest skewness, multiple modes, unusual observations, or differences between datasets.

import matplotlib.pyplot as plt

import numpy as np

rng = np.random.default_rng(42)

read_lengths = rng.normal(150, 15, 1000)

plt.hist(read_lengths, bins=30, edgecolor=”black”)

plt.xlabel(“Read length”)

plt.ylabel(“Frequency”)

plt.title(“Distribution of Sequencing Read Lengths”)

plt.tight_layout()

plt.show()

  • The example uses simulated read lengths drawn from a normal distribution. Actual sequencing data may have a different distribution, including multiple peaks or truncation caused by library preparation and quality filtering. The bin width affects the apparent structure of a histogram, so different bin settings may be worth exploring during exploratory analysis.
  • Box plots summarize a distribution using the median, quartiles, and whiskers, with potential outliers displayed separately according to the plotting convention. They are commonly used to compare gene-expression distributions across experimental groups, assess variation in sequencing quality, or examine protein measurements among sample categories. Violin plots provide related information while also illustrating the estimated distribution density.
  • Seaborn makes it easier to create statistical plots with pandas DataFrames. It provides functions for box plots, violin plots, scatter plots, regression plots, categorical comparisons, and distribution visualization. Its default styling can produce readable figures with less code than a fully customized Matplotlib implementation.

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

df = pd.DataFrame({

    “Condition”: [

        “Control”, “Control”, “Control”,

        “Treatment”, “Treatment”, “Treatment”

    ],

    “Expression”: [10, 12, 11, 18, 22, 20]

})

sns.boxplot(data=df, x=”Condition”, y=”Expression”)

sns.stripplot(

    data=df,

    x=”Condition”,

    y=”Expression”,

    color=”black”,

    alpha=0.7

)

plt.title(“Expression Across Experimental Conditions”)

plt.tight_layout()

plt.show()

  • The box plot summarizes each group, while the strip plot overlays the individual observations. Showing individual measurements can be especially important when sample sizes are small because it allows readers to see the actual data rather than relying exclusively on summary statistics. For larger datasets, points may overlap, so transparency, jitter, or alternative representations may be needed.
  • Heatmaps are widely used in genomics and transcriptomics to display matrices of numerical measurements. In a gene-expression heatmap, rows often represent genes and columns represent samples. Color intensity indicates the magnitude of each measurement or transformed value. Heatmaps can reveal clusters of genes with similar expression patterns, groups of related samples, and potential experimental batch effects.

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

expression = pd.DataFrame(

    [

        [2.1, 2.5, 7.2, 7.8],

        [1.8, 2.0, 6.9, 7.1],

        [7.5, 7.0, 2.3, 2.1],

        [6.8, 7.2, 2.0, 2.5]

    ],

    index=[“Gene_A”, “Gene_B”, “Gene_C”, “Gene_D”],

    columns=[“Control_1”, “Control_2”, “Treatment_1”, “Treatment_2”]

)

sns.heatmap(expression, cmap=”viridis”, annot=True, fmt=”.1f”)

plt.xlabel(“Samples”)

plt.ylabel(“Genes”)

plt.title(“Gene Expression Heatmap”)

plt.tight_layout()

plt.show()

  • This example visualizes illustrative expression values. In real analyses, the color scale and preprocessing should match the data. Gene-expression heatmaps often use normalized and sometimes row-scaled values to emphasize relative patterns across samples. Row scaling changes the interpretation: colors then represent relative expression within each gene rather than absolute expression across all genes. The transformation should be clearly documented, and clustering should be performed using a distance measure appropriate for the data.
  • Matplotlib also supports error bars, confidence bands, annotations, multiple panels, and custom legends. These features are useful for presenting model fits, experimental uncertainty, dose-response relationships, and comparisons between predicted and observed measurements. The subplots() function creates multiple axes within a single figure, allowing related plots to be arranged together. Consistent axis scales, labeling, and formatting make comparisons easier and help prevent misleading visual impressions.

import matplotlib.pyplot as plt

time = [0, 1, 2, 3, 4]

mean_expression = [5, 7, 11, 16, 20]

standard_deviation = [1.0, 1.2, 1.5, 1.3, 1.8]

plt.errorbar(

    time,

    mean_expression,

    yerr=standard_deviation,

    marker=”o”,

    capsize=4

)

plt.xlabel(“Time (hours)”)

plt.ylabel(“Mean expression”)

plt.title(“Expression Measurements with Standard Deviation”)

plt.tight_layout()

plt.show()

  • The error bars in this example represent standard deviations, not confidence intervals. Standard deviation describes variation among observations, whereas a confidence interval quantifies uncertainty in an estimated parameter under a specified method. The figure title and legend should accurately identify the quantity being displayed.
  • Plotly is a library for interactive data visualization. Unlike conventional static plots, Plotly figures can support hovering, zooming, panning, selecting observations, and interactive legends. These features are useful when exploring large datasets or sharing visual summaries through notebooks, web applications, and reports. Interactive scatter plots can display gene identifiers or sample metadata when a user moves the pointer over a point. Plotly is particularly helpful when static figures cannot communicate the full detail of a complex dataset.
  • Bokeh is another library for interactive browser-based visualizations. It supports linked plots, interactive controls, and dashboards. Researchers can use it to build interfaces for exploring genomic measurements, comparing samples, and inspecting experimental results. Altair provides a declarative approach to visualization, in which users specify the data, visual encodings, and plot structure. It is often convenient for concise statistical graphics and exploratory data analysis, particularly when the dataset can be represented effectively within its supported data workflow.
  • Other libraries serve more specialized purposes. Plotnine provides a grammar-of-graphics interface similar to that used by ggplot2 in R. Pygal can produce certain interactive SVG-based charts. NetworkX can be used with Matplotlib or other visualization tools to display biological interaction networks, while graph visualization systems may be more appropriate for very large networks. For protein structures, molecular visualization tools such as PyMOL and ChimeraX provide specialized three-dimensional representations that ordinary statistical plotting libraries do not replace.
  • Bioinformatics also includes many data types that require domain-specific visualization methods. Sequence logos can display conserved nucleotide or amino acid patterns within sequence motifs. Genome browsers show genomic coordinates, gene annotations, sequencing coverage, and variant locations. Phylogenetic trees represent evolutionary relationships among organisms, genes, or proteins. Circos-style plots visualize relationships among genomic regions, while dot plots can help reveal sequence similarity, repeats, and rearrangements. Specialized packages and dedicated applications are generally more appropriate for these tasks than ordinary line charts or scatter plots.
  • Single-cell RNA sequencing generates high-dimensional gene-expression profiles that are often visualized using dimensionality-reduction methods. Principal component analysis (PCA), t-distributed stochastic neighbor embedding (t-SNE), and Uniform Manifold Approximation and Projection (UMAP) can produce two-dimensional or three-dimensional representations of samples or cells. These visualizations help reveal clusters and potential biological structure, but they do not independently prove that distinct cell types or biological states exist. Results depend on preprocessing, feature selection, model parameters, and the properties of the dimensionality-reduction method.
  • Libraries such as Scanpy support single-cell analysis workflows, including quality control, dimensionality reduction, clustering, and visualization. Its plotting functions can generate PCA plots, UMAP projections, expression overlays, and marker-gene visualizations. AnnData commonly stores the expression matrix alongside observation metadata, variable metadata, and analysis results. These tools are more suitable for full single-cell workflows than attempting to manage every stage with Matplotlib alone, although Matplotlib can still be used to customize many resulting figures.
  • Visualization of genomic and experimental data also requires careful treatment of statistical uncertainty. A graph should communicate the number of biological replicates, the meaning of error bars, the scale of the axes, and the transformations applied to the data. Logarithmic scales can be useful when values span several orders of magnitude, but they change the visual interpretation and cannot directly display nonpositive values on a standard logarithmic axis. Truncated axes, inappropriate color scales, and inconsistent plotting ranges can exaggerate differences or conceal important patterns.
  • Color selection is important for scientific communication. Color palettes should remain interpretable for readers with color-vision deficiencies and should preserve adequate contrast. Sequential palettes are often suitable for values that increase continuously, diverging palettes for measurements centered on a meaningful midpoint, and categorical palettes for distinct groups. When possible, plots should not depend on color alone; markers, line styles, labels, or other visual distinctions can provide additional information. For heatmaps, a color bar should identify the numerical range and explain what the colors represent.
  • Large biological datasets can create visualization challenges because millions of points may overlap or exceed the practical limits of interactive rendering. Strategies such as aggregation, sampling, density plots, hexagonal binning, rasterization, and downsampling can improve readability and performance. Any sampling or filtering should be documented, particularly when it might change the apparent distribution or conceal rare biological populations. Data visualization should simplify interpretation without distorting the underlying evidence.
  • Matplotlib figures can be saved to common formats using savefig(). PNG is useful for many digital reports, SVG and PDF are suitable for scalable vector graphics, and other formats may be appropriate depending on the publication requirements. The resolution, dimensions, font sizes, line widths, and figure layout should be chosen for the intended display medium.

import matplotlib.pyplot as plt

values = [12, 18, 15, 24]

labels = [“A”, “B”, “C”, “D”]

plt.bar(labels, values)

plt.xlabel(“Group”)

plt.ylabel(“Measurement”)

plt.title(“Illustrative Biological Measurements”)

plt.tight_layout()

plt.savefig(“biological_measurements.png”, dpi=300, bbox_inches=”tight”)

plt.savefig(“biological_measurements.pdf”, bbox_inches=”tight”)

plt.show()

  • Saving figures in multiple formats supports different downstream uses, from presentations to publication-ready documents. Researchers should inspect the saved files because fonts, layout, and rendering may differ across formats. Figure captions should describe the biological question, dataset, sample sizes, units, preprocessing, statistical methods, and relevant abbreviations so that the figure can be interpreted independently of the surrounding text.
  • An effective visualization workflow begins by identifying the scientific question and the type of data being examined. The researcher then checks data quality, selects a suitable graphical representation, chooses meaningful axes and scales, adds labels and legends, and assesses whether the figure communicates the intended message accurately. Where necessary, statistical analysis should complement visual inspection rather than be replaced by it. Reproducible plotting scripts should record relevant preprocessing choices and software versions so that figures can be regenerated when data or methods change.
  • In conclusion, data visualization is a fundamental skill in bioinformatics because it transforms complex biological measurements into interpretable graphical representations. Matplotlib provides flexible control over static scientific figures, Seaborn simplifies statistical graphics, Plotly and Bokeh support interactive exploration, and specialized libraries such as Scanpy address particular biological data types. By choosing suitable plots, presenting uncertainty clearly, using appropriate color scales, and documenting preprocessing, researchers can improve exploratory analysis, detect errors, communicate results, and support reliable scientific conclusions across genomics, transcriptomics, proteomics, and computational biology.
Author:

Leave a Reply

Your email address will not be published. Required fields are marked *