0% found this document useful (0 votes)
31 views

Data Visualization With Ggplot2 - CheatSheet

The document describes 27 sections covering various techniques for creating data visualizations using the ggplot2 package in R. It covers topics such as basic and advanced plot types, aesthetics, faceting, themes, scales, annotations, saving plots, statistical transformations, custom geoms, interactive plots, geospatial visualization, and performance optimizations. The document serves as a comprehensive cheat sheet for leveraging the full capabilities of ggplot2 to build custom statistical graphics and visualizations.

Uploaded by

Juan Casaboza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Data Visualization With Ggplot2 - CheatSheet

The document describes 27 sections covering various techniques for creating data visualizations using the ggplot2 package in R. It covers topics such as basic and advanced plot types, aesthetics, faceting, themes, scales, annotations, saving plots, statistical transformations, custom geoms, interactive plots, geospatial visualization, and performance optimizations. The document serves as a comprehensive cheat sheet for leveraging the full capabilities of ggplot2 to build custom statistical graphics and visualizations.

Uploaded by

Juan Casaboza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

# [ Data Visualization With ggplot2 ] ( CheatSheet )

1. Basic Plot Types

● Scatter Plot: ggplot(data, aes(x, y)) + geom_point()


● Line Plot: ggplot(data, aes(x, y)) + geom_line()
● Bar Chart: ggplot(data, aes(x, y)) + geom_bar(stat='identity')
● Histogram: ggplot(data, aes(x)) + geom_histogram()
● Density Plot: ggplot(data, aes(x)) + geom_density()
● Box Plot: ggplot(data, aes(x, y)) + geom_boxplot()
● Violin Plot: ggplot(data, aes(x, y)) + geom_violin()
● Dot Plot: ggplot(data, aes(x, y)) + geom_dotplot()
● Area Plot: ggplot(data, aes(x, y)) + geom_area()
● Stacked Bar Chart: ggplot(data, aes(x, fill=category)) + geom_bar()

2. Aesthetics

● Color: ggplot(data, aes(x, y, color=category)) + geom_point()


● Fill: ggplot(data, aes(x, y, fill=category)) + geom_bar()
● Shape: ggplot(data, aes(x, y, shape=category)) + geom_point()
● Size: ggplot(data, aes(x, y, size=value)) + geom_point()
● Alpha: ggplot(data, aes(x, y, alpha=value)) + geom_point()
● Linetype: ggplot(data, aes(x, y, linetype=category)) + geom_line()

3. Facets for Conditional Plots

● Facet Grid: ggplot(data, aes(x, y)) + geom_point() +


facet_grid(rows ~ cols)
● Facet Wrap: ggplot(data, aes(x, y)) + geom_point() + facet_wrap(~
category)

4. Themes and Customization

● Theme Minimal: ggplot(data, aes(x, y)) + geom_point() +


theme_minimal()
● Theme Classic: ggplot(data, aes(x, y)) + geom_point() +
theme_classic()

By: Waleed Mousa


● Customizing Themes: ggplot(data, aes(x, y)) + geom_point() +
theme(axis.text.x = element_text(angle = 90))
● Removing Legend: ggplot(data, aes(x, y)) + geom_point() +
theme(legend.position = "none")
● Changing Plot Background: ggplot(data, aes(x, y)) + geom_point() +
theme(plot.background = element_rect(fill = "lightblue"))

5. Scale and Coordinate Transformations

● Logarithmic Scale: ggplot(data, aes(x, y)) + geom_point() +


scale_y_log10()
● Reverse Scale: ggplot(data, aes(x, y)) + geom_point() +
scale_y_reverse()
● Date Scale: ggplot(data, aes(x, y)) + geom_point() +
scale_x_date(date_breaks = "1 month", date_labels = "%b")
● Coordinate Flip: ggplot(data, aes(x, y)) + geom_bar() +
coord_flip()
● Polar Coordinates: ggplot(data, aes(x, y)) + geom_bar() +
coord_polar()

6. Statistical Transformations

● Smooth Line (Regression): ggplot(data, aes(x, y)) +


geom_smooth(method = 'lm')
● Bin Counting: ggplot(data, aes(x)) + geom_histogram(binwidth = 10)
● Cumulative Distribution: ggplot(data, aes(x)) + stat_ecdf()
● Quantile Regression: ggplot(data, aes(x, y)) + geom_quantile()
● Density 2D: ggplot(data, aes(x, y)) + geom_density_2d()

7. Labels and Annotations

● X and Y Labels: ggplot(data, aes(x, y)) + geom_point() + xlab("X


Axis Label") + ylab("Y Axis Label")
● Plot Title: ggplot(data, aes(x, y)) + geom_point() + ggtitle("Plot
Title")
● Text Annotation: ggplot(data, aes(x, y)) + geom_point() +
annotate("text", x = 10, y = 5, label = "Annotation")

By: Waleed Mousa


● Customizing Axis Text: ggplot(data, aes(x, y)) + geom_point() +
theme(axis.text.x = element_text(face = "bold", color = "red"))

8. Combining Multiple Plots

● Layers: ggplot(data, aes(x, y)) + geom_point() + geom_smooth()


● Multiple Geometries: ggplot(data, aes(x, y)) + geom_point() +
geom_line()
● Using Patchwork for Arranging Plots: plot1 / plot2 +
plot_layout(ncol = 1)

9. Saving Plots

● ggsave to Save Plots: ggsave("plot.png", plot, width = 10, height =


8, dpi = 300)

10. Advanced Data Manipulation within ggplot2

● dplyr for Data Manipulation: ggplot(data %>% filter(value > 10),


aes(x, y)) + geom_point()
● Statistical Summary: ggplot(data, aes(x, y)) + stat_summary(fun =
"mean", geom = "point")

11. Customizing with ggplot2 Extensions

● gganimate for Animations: ggplot(data, aes(x, y, frame = time)) +


geom_point() + transition_time(time)
● ggtree for Phylogenetic Trees: ggtree(tree_data) + geom_tiplab()

12. Working with Maps and Spatial Data

● geom_sf for Simple Features: ggplot() + geom_sf(data =


spatial_data)
● geom_map for Map Data: ggplot() + geom_map(data = map_data, map =
map_data)
● geom_tile for Heatmaps: ggplot(data, aes(x, y, fill = value)) +
geom_tile()

13. Custom and Composite Geometries

By: Waleed Mousa


● geom_rug for Marginal Rugs: ggplot(data, aes(x, y)) + geom_point()
+ geom_rug()
● geom_jitter for Adding Jitter to Points: ggplot(data, aes(x, y)) +
geom_jitter()
● geom_hex for Hexbin Plots: ggplot(data, aes(x, y)) + geom_hex()
● Custom Geom Function: geom_custom <- function(...) { layer(stat =
"custom", geom = "point", ...) }
● Creating Custom Stat Functions: StatCustom <- ggproto("StatCustom",
Stat, compute_group = function(data, scales) { /* custom
computations */ })

14. Customizing Scales and Guides

● Setting Manual Scales for Colors: ggplot(data, aes(x, y,


color=category)) + geom_point() +
scale_color_manual(values=c("red", "blue", "green"))
● Logarithmic Scales: ggplot(data, aes(x, y)) + geom_point() +
scale_y_log10()
● Date Scales for Time Series: ggplot(data, aes(x, y)) + geom_line()
+ scale_x_date(date_breaks = "1 month", date_labels = "%b %Y")
● Continuous Scale with Custom Limits: ggplot(data, aes(x, y)) +
geom_point() + scale_x_continuous(limits=c(0, 100))
● Discrete Scale with Custom Labels: ggplot(data, aes(x, y)) +
geom_bar() + scale_x_discrete(labels=c("One", "Two", "Three"))
● Customizing Date Scale Breaks and Labels: ggplot(data, aes(x, y))
+ scale_x_date(date_breaks = "1 week", date_labels = "%d-%m-%Y")
● Setting Manual Scale for Fill Aesthetics: ggplot(data, aes(x, y))
+ geom_tile() + scale_fill_gradient(low = "blue", high = "red")

15. Advanced Theming

● Modifying Text Elements: ggplot(data, aes(x, y)) + geom_point() +


theme(text = element_text(size=20, face="bold"))
● Customizing Axis Ticks and Labels: ggplot(data, aes(x, y)) +
geom_point() + theme(axis.text.x = element_text(angle=90, hjust=1))
● Removing Plot Components (e.g., Axis): ggplot(data, aes(x, y)) +
geom_point() + theme(axis.title.x = element_blank())

By: Waleed Mousa


● Modifying Legend Position and Appearance: ggplot(data, aes(x, y,
color=category)) + geom_point() + theme(legend.position = "bottom")

16. Statistical Operations and Computations

● Computing and Displaying Regression Lines: ggplot(data, aes(x, y))


+ geom_point() + geom_smooth(method = "lm")
● Displaying Confidence Intervals: ggplot(data, aes(x, y)) +
geom_smooth()
● Creating 2D Density Plots: ggplot(data, aes(x, y)) +
geom_density_2d()
● Binomial Proportion with Confidence Intervals: ggplot(data, aes(x,
y)) + stat_binomial()

17. Multi-panel Plots

● Creating Facets (Split by a Single Variable): ggplot(data, aes(x,


y)) + geom_point() + facet_wrap(~category)
● Creating Facets (Split by Two Variables): ggplot(data, aes(x, y))
+ geom_point() + facet_grid(rows_var ~ cols_var)
● Customizing Facet Labels: ggplot(data, aes(x, y)) + geom_point() +
facet_wrap(~category, labeller = label_both)

18. Annotations and Reference Lines

● Adding Text Annotations: ggplot(data, aes(x, y)) + geom_point() +


annotate("text", x = 50, y = 50, label = "Annotation")
● Adding Reference Lines: ggplot(data, aes(x, y)) + geom_point() +
geom_hline(yintercept=mean(data$y), linetype="dashed")
● Adding Highlighted Regions: ggplot(data, aes(x, y)) +
geom_rect(aes(xmin=0, xmax=50, ymin=20, ymax=80), fill="blue",
alpha=0.3)

19. Saving and Exporting Plots

● Saving Plots to File (e.g., PNG, PDF): ggsave("plot.png", plot,


width = 10, height = 8, dpi = 300)
● Saving Plots with Specific Dimensions and Resolutions:
ggsave("plot.pdf", plot, width = 11, height = 8.5)

By: Waleed Mousa


20. Interactive Plots with ggplot2 Extensions

● Creating Interactive ggplot2 Plots with plotly:


ggplotly(ggplot(data, aes(x, y)) + geom_point())
● Creating Interactive Plots with ggiraph: ggiraph(code =
{print(ggplot(data, aes(x = x, y = y)) +
geom_point_interactive(aes(tooltip = label, data_id = id)))})

21. Geospatial Visualization

● Creating Maps with geom_sf: ggplot() + geom_sf(data = spatial_data)


● Overlaying Points on a Map: ggplot() + geom_sf(data = spatial_data)
+ geom_point(data = points_data, aes(x = lon, y = lat))
● Thematic Maps with fill Aesthetics: ggplot() + geom_sf(data =
spatial_data, aes(fill = variable))

22. Complex Layouts and Nested Plots

● Arranging Multiple Plots: grid.arrange(plot1, plot2, ncol = 2)


● Creating Inset Plots: plot + inset_element(plot = inset_plot, left
= 0.5, bottom = 0.5, width = 0.25, height = 0.25)

23. Custom Geoms and Statistical Transformations

● Creating Custom Geoms: StatCustomGeom <- ggproto("StatCustomGeom",


Stat, compute_group = function(data, scales) { # Custom computation
})
● Using Custom Stats in Plots: ggplot(data, aes(x, y)) +
geom_line(stat = "custom_stat")

24. Animation and Transition

● Creating Animated Plots with gganimate: ggplot(data, aes(x, y,


frame = time)) + geom_point() + transition_states(states)

25. Extensions for Specific Types of Data or Plots

● Complex Heatmaps with ggplot2: ComplexHeatmap::Heatmap(matrix_data)

By: Waleed Mousa


● Genomic Data Visualization with ggbio: ggbio::autoplot(object,
aes(x = x, y = y))

26. Performance Improvements

● Using Data Tables for Large Datasets: ggplot(data.table(data),


aes(x, y)) + geom_point()
● Optimizing Plot Rendering with ragg: agg_png("plot.png", width =
1000, height = 800, res = 150)

27. Customizing Plot Aesthetics

● Adding Custom Fonts: showtext::showtext_auto(); ggplot(data, aes(x,


y)) + geom_text(aes(label = label), family = "my_custom_font")
● Modifying ggplot2 Themes: theme_set(theme_minimal() +
theme(plot.background = element_rect(fill = "white")))
● Customizing Legend Title and Labels: ggplot(data, aes(x, y,
fill=group)) + geom_bar() + scale_fill_discrete(name = "Legend
Title", labels = c("Group 1", "Group 2"))
● Modifying Axis Labels and Text: ggplot(data, aes(x, y)) +
geom_point() + theme(axis.text.x = element_text(angle = 45, hjust =
1))

28. Using Different Plot Geometries

● Using geom_raster for Heatmaps: ggplot(data, aes(x, y, fill =


value)) + geom_raster()
● Creating Ridgeline Plots: ggplot(data, aes(x, y)) +
geom_ridgeline()
● Creating 3D Surface Plots: plotly::plot_ly(data, x = ~x, y = ~y, z
= ~z, type = "surface")

29. Multi-layer Plots

● Combining Multiple Layers in a Plot: ggplot(data, aes(x, y)) +


geom_point() + geom_smooth()
● Using Geoms with Conditional Aesthetics: ggplot(data, aes(x, y)) +
geom_point(data = subset(data, condition), aes(color = category))

By: Waleed Mousa


30. Conditional Elements and Aesthetics

● Conditional Colors Based on Values: ggplot(data, aes(x, y)) +


geom_point(aes(color = ifelse(value > threshold, "Above",
"Below")))
● Conditional Plot Elements with ifelse in Aesthetics: ggplot(data,
aes(x, y)) + geom_point(aes(shape = ifelse(condition, shape1,
shape2)))

31. Advanced Text and Labeling

● Adding Mathematical Expressions in Labels: ggplot(data, aes(x, y))


+ ylab(expression(paste("Rate (", mu, "mol / m"^2* "s"^{-1}, ")")))
● Using Direct Labels for Points: ggplot(data, aes(x, y)) +
geom_point() + geom_text(aes(label = labels), hjust = 1, vjust = 1)

32. Customizing Legends

● Removing Legends: ggplot(data, aes(x, y)) + geom_point() +


theme(legend.position = "none")
● Positioning and Layout of Legends: ggplot(data, aes(x, y)) +
geom_point() + theme(legend.position = "bottom", legend.direction =
"horizontal")
● Customizing Legend Keys: ggplot(data, aes(x, y)) + geom_point() +
guides(color = guide_legend(override.aes = list(shape = 16)))

33. Advanced Faceting

● Facet Grid with Formulas: ggplot(data, aes(x, y)) + geom_point() +


facet_grid(rows ~ cols)
● Facet Wrap with Scales: ggplot(data, aes(x, y)) + geom_point() +
facet_wrap(~ category, scales = "free")

34. Specialized Plots and Techniques

● Creating Network Graphs with ggraph: ggraph(graph, layout = 'fr')


+ geom_edge_link() + geom_node_point()
● Creating Heatmaps with ComplexHeatmap:
ComplexHeatmap::Heatmap(matrix_data)

By: Waleed Mousa


35. Performance and Large Data Handling

● Using Data Tables for Large Datasets: ggplot(data.table(data),


aes(x, y)) + geom_point()
● Optimizing ggplot2 Performance: ggplot(data, aes(x, y)) +
geom_point() + coord_cartesian(clip = 'off')

By: Waleed Mousa

You might also like