Welcome back to your course on computational biology. In our last lesson, we focused on the crucial skill of data wrangling, using the tidyverse to transform raw data into a "tidy" format. You learned how to use tools like dplyr and tidyr to reshape and clean tables, preparing them for analysis. This was a vital step, because the structure of your data fundamentally determines your ability to visualize it effectively.
Today, we'll build directly on that foundation. You'll learn to recreate complex exploratory visualizations using ggplot2, the premier data visualization package in R. ggplot2 is more than just a plotting library; it's an implementation of the "Grammar of Graphics," a systematic approach for building plots layer by layer. This will allow you to move from simple charts to nuanced, publication-quality figures that can reveal deep patterns in biological data. Given your experience in research and your goal of pursuing a PhD, mastering this tool is essential for both exploring your data and communicating your findings.
The Grammar of Graphics: A New Way of Thinking About Plots
At its core, a ggplot2 visualization is built from three essential components:
- Data: The tidy
data.frameortibbleyou want to plot. - Aesthetics (
aes): A mapping from variables in your data to visual properties of the plot, such as x/y position, color, shape, and size. - Geometries (
geom): The geometric objects (like points, lines, or bars) that represent the data on the plot.
Everything else—labels, themes, scales, and facets—is an additional layer you add to refine and enhance your plot. This layered approach is incredibly powerful, allowing for immense flexibility and customization.
To get a quick, high-level overview of this philosophy, the following video provides an excellent introduction using the palmerpenguins dataset. It clearly explains the "data, aesthetics, geometry" trinity.
Data visualization with ggplot
This video from the "R Programming 101" channel introduces the core concepts of ggplot2.
Watch the first three sections, from the beginning up to the start of the detailed code walkthrough. Focus on the conceptual explanation of the three main components: defining the data, mapping aesthetics, and defining the geometry.
Building a Biological Plot, Layer by Layer
Now let's apply these concepts to a biological dataset. We will use a resource from Data Carpentry that uses a tidy dataset of genomic variants, which should feel familiar from your work in molecular microbiology and genetics. This will guide you through creating a plot step-by-step.
Data Analysis and Visualization with R for Genomics: Data Visualization with ggplot2
This Data Carpentry lesson provides a hands-on, iterative introduction to building plots with ggplot2. We'll use this to create our first visualization and see the Grammar of Graphics in action.
Please read through the following sections: Introduction to ggplot2: Start at the beginning and read the introduction to the Grammar of Graphics. This reinforces the core philosophy. Loading the dataset: Follow the instructions in the "Loading the dataset" section. This involves loading the required tidyverse packages and the variants data file. Building your plots iteratively: This is the most important section for this part of the lesson. Work through the text and code from "Building your plots iteratively". Pay close attention to how the plot is constructed: Start with ggplot(data = variants, aes(x = POS, y = DP)). Add a layer with + geom_point(). Modify the geom with alpha and color arguments. Map a data variable to an aesthetic like color = sample_id. Add labs() and save the plot with ggsave(). Try to run the code examples in your own R environment as you go.
Expanding Your Visual Vocabulary
A scatter plot is a great start, but exploratory data analysis often requires a wider range of plot types to answer different kinds of questions. For example, how do you compare the distribution of a single continuous variable across multiple categories? Bar plots of means can be misleading, as they hide the underlying distribution.
The textbook Modern Statistics for Modern Biology offers an excellent survey of visualization techniques for 1D and 2D data, contextualized with real gene expression data.
3 Data visualization – Modern Statistics for Modern Biology
This chapter provides a sophisticated look at different visualization types and their appropriate uses in biology. It will expand your toolkit for exploratory analysis.
Please read the following two sections: Visualizing data in 1D: Read through Section 3.6, which covers a variety of plots for visualizing distributions. Pay special attention to the comparison between barplots, boxplots, violin plots, and density plots. The text makes a strong case for why plots that show the distribution (like boxplots and violin plots) are superior to those that only show a summary (like barplots). Visualizing data in 2D: scatterplots: Skim through Section 3.7. You've already made a scatter plot, but this section introduces important techniques for dealing with overplotting, such as adjusting transparency (alpha) and using 2D density plots.
A Case Study: Visualizing Gene Expression Data
We've now covered the theory and seen several plot types. Let's put it all together in a practical workflow. The following video demonstrates a complete analysis of gene expression data using ggplot2, perfectly mirroring the kind of task you might encounter in a quantitative biology lab.
The video covers creating density and violin plots to compare distributions, building scatter plots to see correlations between genes, and adding regression lines with geom_smooth. Crucially, it shows how to do this for different sample groups within the same plot, a powerful technique for comparative analysis.
Visualize gene expression data in R using ggplot2 | Bioinformatics for beginners
This video from the "Bioinformagician" channel is a fantastic walkthrough of a real-world bioinformatics visualization task.
Please watch the following segments. I encourage you to follow along with your own R session if you feel comfortable. Density & Violin Plots: Watch how the presenter compares gene expression distributions between two tissue types using geom_density and then converts this to a geom_violin plot. This is a practical application of the concepts from the textbook you just read. Correlation with Regression Lines: The presenter then investigates the correlation between two genes. Watch how a basic scatter plot is augmented with a linear regression line using geom_smooth, first for all data (single line) and then for different sample types separately (multiple lines). This demonstrates how to map aesthetics within geom_smooth to create conditional trend lines. Heatmaps with ggplot2: The presenter creates a heatmap using geom_tile. This is a common visualization for high-throughput data. Watch the segment from creating the heatmap to see how data is mapped to the fill aesthetic and how the color scale is customized. Saving Your Plots: Finally, learn how to save your work for publications or reports using ggsave in the segment from saving plots.
Conclusion
In this lesson, you have learned how to harness the Grammar of Graphics to create powerful and informative biological visualizations with ggplot2. We've moved from the basic components of a plot to recreating complex, multi-layered figures that are essential for modern biological research.
Key takeaways from this lesson:
- The Grammar of Graphics: Every
ggplot2plot is composed of data, aesthetic mappings, and geometries. - Layered Construction: You build plots iteratively by adding layers (
+), such as geoms, scales, themes, and labels. - A Rich Visual Vocabulary: You are now familiar with a range of
geomsfor visualizing relationships (geom_point,geom_smooth), distributions (geom_boxplot,geom_violin,geom_density), and categorical data (geom_bar). - Advanced Techniques: You've seen how to handle overplotting with transparency, use faceting to create small multiples (as seen in the Data Carpentry resource), and add conditional layers like group-specific regression lines.
You now have the skills to not only make a plot but to thoughtfully design a visualization that best answers your biological question.
In our next lesson, we will zoom out from the notebook to the entire project. Having created data, code, and figures, how do we organize them all in a way that is logical, portable, and reproducible? We'll tackle this by learning how to structure a complete research repository.