Last updated: 2025-10-15

Checks: 6 1

Knit directory: data_visualization_in_R/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown is untracked by Git. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20251007) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 9e1856e. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Untracked files:
    Untracked:  analysis/01_intro_data_viz.Rmd
    Untracked:  analysis/02_intro_to_ggplot2.Rmd
    Untracked:  analysis/03_heatmap_demystified.Rmd
    Untracked:  analysis/04_practical_scRNAseq_viz.Rmd

Unstaged changes:
    Modified:   analysis/about.Rmd
    Modified:   analysis/index.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


There are no past versions. Publish this analysis with wflow_publish() to start tracking its development.


The Power of Data Visualization

Data visualization is the graphical representation of information and data. In an age where we generate data at an unprecedented rate, the ability to create clear, compelling visualizations has become crucial for understanding patterns, communicating findings, and making data-driven decisions.

“A picture is worth a thousand words” - especially when that picture represents complex data patterns that would be nearly impossible to detect in tables of numbers.

Why Visualize Data?

1. Pattern Recognition

Human brains are exceptionally good at processing visual information. We can quickly spot trends, outliers, and relationships in graphical data that might take hours to detect in numerical tables.

2. Communication

Visualizations can communicate complex findings to diverse audiences - from fellow researchers to policymakers to the general public.

3. Exploration

Visualization is a powerful tool for exploratory data analysis, helping researchers discover unexpected patterns and generate new hypotheses.

4. Validation

Visual inspection can help identify data quality issues, outliers, and assumptions that might not be obvious from summary statistics alone.

The Genomics Visualization Landscape

If you read genomics papers regularly, you’ll notice that most figures fall into just six categories:

  1. Scatter plots - for correlation analysis and gene expression relationships
  2. Bar plots - for comparing quantities across groups
  3. Line plots - for showing trends over time or conditions
  4. Box plots/Violin plots - for comparing distributions across groups
  5. Histograms - for understanding data distributions
  6. Heatmaps - for visualizing large matrices of data (gene expression, etc.)

Mastering these six types will enable you to reproduce approximately 90% of figures in genomics literature.

Principles of Effective Data Visualization

1. Know Your Audience

  • Scientific peers: Detailed, precise, with statistical information
  • General public: Simple, clear, with minimal jargon
  • Policymakers: Focused on actionable insights

2. Choose the Right Chart Type

Data Type Relationship Best Chart Type
Continuous vs Continuous Correlation Scatter plot
Categorical vs Continuous Distribution comparison Box plot, Violin plot
Single continuous variable Distribution Histogram
Categories vs Quantities Comparison Bar plot
Time series Trends Line plot
Matrix data Patterns in 2D Heatmap

3. Design Principles

Clarity Over Beauty

  • Prioritize understanding over aesthetics
  • Remove unnecessary elements (chartjunk)
  • Use consistent styling

Accessibility

  • Use colorblind-friendly palettes
  • Include proper legends and labels
  • Ensure sufficient contrast

Accuracy

  • Start axes at zero when appropriate
  • Use appropriate scales
  • Don’t distort data relationships

4. Color Usage

Sequential Colors (for ordered data)

  • Light to dark of single hue
  • Good for: heatmaps, choropleth maps
  • Example: gene expression levels

Diverging Colors (for data with meaningful center)

  • Two hues meeting at neutral center
  • Good for: correlation matrices, fold changes
  • Example: up/down regulated genes

Categorical Colors (for distinct groups)

  • Distinct, equally prominent hues
  • Good for: different cancer types, treatment groups
  • Avoid: red/green combinations (colorblind unfriendly)

Common Visualization Mistakes

1. The Misleading Y-Axis

Starting bar charts at non-zero values can exaggerate differences.

2. Too Many Categories

More than 7-8 categories become difficult to distinguish, especially with color.

3. Pie Chart Overuse

Pie charts are difficult to interpret precisely. Bar charts are usually better.

4. 3D Effects

3D charts are often harder to read and can distort data perception.

5. Poor Color Choices

  • Using red/green for comparisons (colorblind issues)
  • Not enough contrast
  • Too many similar colors

The Grammar of Graphics

The Grammar of Graphics is a theoretical framework for data visualization that underlies ggplot2. It breaks down visualizations into fundamental components:

Core Components:

  1. Data: The dataset you want to visualize
  2. Aesthetics (aes): How data variables map to visual properties
    • Position (x, y)
    • Color, fill
    • Size, shape
    • Transparency (alpha)
  3. Geometries (geom): The visual elements that represent data
    • Points, lines, bars, boxes
  4. Statistics (stat): Statistical transformations of data
    • Counts, means, regression lines
  5. Scales: Control how aesthetics map to data values
    • Color scales, axis scales
  6. Coordinate systems: How data is mapped to the plane
    • Cartesian, polar, map projections
  7. Facets: Subplots for different subsets of data
  8. Themes: Overall visual appearance

The Layered Approach

ggplot2 builds visualizations by adding layers:

ggplot(data = mydata, aes(x = var1, y = var2)) +  # Base layer
  geom_point() +                                   # Geometry layer
  geom_smooth(method = "lm") +                     # Additional geometry
  scale_color_brewer(type = "qual") +              # Scale layer
  theme_minimal() +                                # Theme layer
  labs(title = "My Plot")                          # Labels layer

This modular approach makes ggplot2 extremely flexible and powerful.

Data Visualization in Scientific Research

Pre-Analysis Visualization

  • Data exploration: Understanding distributions, identifying outliers
  • Quality control: Spotting data collection issues
  • Hypothesis generation: Discovering unexpected patterns

Analysis Visualization

  • Results presentation: Showing statistical findings
  • Model diagnostics: Checking assumptions, residuals
  • Sensitivity analysis: Exploring robustness of findings

Communication Visualization

  • Publication figures: Journal-ready visualizations
  • Presentations: Conference talks, seminars
  • Reports: Technical documentation

Best Practices for Scientific Visualization

1. Reproducibility

  • Use code-based tools (like R) rather than point-and-click software
  • Document your visualization code
  • Use version control for your analysis scripts

2. Statistical Honesty

  • Show uncertainty (error bars, confidence intervals)
  • Don’t cherry-pick flattering visualizations
  • Include sample sizes and statistical tests when relevant

3. Ethical Considerations

  • Don’t manipulate scales to exaggerate effects
  • Be transparent about data filtering or transformations
  • Consider the broader implications of your visualizations

Tools and Resources

R Ecosystem for Visualization

  • ggplot2: The gold standard for statistical graphics
  • plotly: Interactive visualizations
  • gganimate: Animated plots
  • patchwork: Combining multiple plots

Color Resources

  • ColorBrewer: Scientifically-designed color palettes
  • Viridis: Perceptually uniform, colorblind-friendly palettes
  • RColorBrewer: R implementation of ColorBrewer

Inspiration and Learning

References

Essential reading for mastering data visualization:

  1. Fundamentals of Data Visualization by Claus O. Wilke
    • Comprehensive guide to visualization principles
    • Covers theory and practical applications
    • Excellent for understanding when to use different chart types
  2. Data Visualization by Kieran Healy
    • Practical approach with R and ggplot2
    • Focus on social science applications
    • Great for learning ggplot2 syntax and concepts
  3. ggplot2: Elegant Graphics for Data Analysis by Hadley Wickham
    • The definitive guide to ggplot2
    • Written by the package creator
    • Essential reference for advanced ggplot2 techniques

Next Steps

Now that you understand the principles of effective data visualization, you’re ready to start creating your own visualizations. In the next lesson, we’ll dive into practical ggplot2 programming using real cancer genomics data.

Continue to: Lesson 2: Practical ggplot2


sessionInfo()
R version 4.4.1 (2024-06-14)
Platform: aarch64-apple-darwin20
Running under: macOS Sonoma 14.1

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: America/New_York
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] workflowr_1.7.1

loaded via a namespace (and not attached):
 [1] vctrs_0.6.5       httr_1.4.7        cli_3.6.3         knitr_1.48       
 [5] rlang_1.1.4       xfun_0.52         stringi_1.8.4     processx_3.8.4   
 [9] promises_1.3.0    jsonlite_1.8.8    glue_1.8.0        rprojroot_2.0.4  
[13] git2r_0.35.0      htmltools_0.5.8.1 httpuv_1.6.15     ps_1.7.7         
[17] sass_0.4.9        fansi_1.0.6       rmarkdown_2.27    jquerylib_0.1.4  
[21] tibble_3.2.1      evaluate_0.24.0   fastmap_1.2.0     yaml_2.3.10      
[25] lifecycle_1.0.4   whisker_0.4.1     stringr_1.5.1     compiler_4.4.1   
[29] fs_1.6.4          pkgconfig_2.0.3   Rcpp_1.0.13       rstudioapi_0.16.0
[33] later_1.3.2       digest_0.6.36     R6_2.5.1          utf8_1.2.4       
[37] pillar_1.9.0      callr_3.7.6       magrittr_2.0.3    bslib_0.8.0      
[41] tools_4.4.1       cachem_1.1.0      getPass_0.2-4