ggplot2
Build layered plots with geoms, facets, and themes using the grammar of graphics.
Code
library(ggplot2)
set.seed(1)
df <- data.frame(
group = rep(c("A", "B", "C"), each = 30),
value = c(rnorm(30, 5), rnorm(30, 7), rnorm(30, 6))
)
# Scatter with smoothing
p1 <- ggplot(df, aes(x = seq_along(value), y = value, color = group)) +
geom_point(alpha = 0.6) +
geom_smooth(method = "loess") +
labs(title = "Values by group", x = "index", y = "value") +
theme_minimal()
print(p1)
# Boxplot
p2 <- ggplot(df, aes(x = group, y = value, fill = group)) +
geom_boxplot() +
stat_summary(fun = mean, geom = "point", color = "red")
print(p2)
# Histogram with facet
p3 <- ggplot(df, aes(value)) +
geom_histogram(bins = 15, fill = "steelblue", color = "white") +
facet_wrap(~ group) +
labs(title = "Distribution per group")
print(p3)
# Bar chart of means
means <- aggregate(value ~ group, df, mean)
p4 <- ggplot(means, aes(group, value, fill = group)) +
geom_col() +
geom_text(aes(label = sprintf("%.2f", value)), vjust = -0.5)
print(p4)
# Save to file
# ggsave("plot.png", p1, width = 6, height = 4)Explanation
ggplot2 builds plots in layers using the grammar of graphics, starting with a data and aes mapping and adding geoms such as point, smooth, or boxplot. Faceting splits the plot into small multiples by a categorical variable. Save with ggsave to write any plot to a file in the desired format.
More R Snippets
Data Frames
Create, inspect, filter, mutate, sort, aggregate, and merge data frames.
Vectors
Build atomic vectors, apply vectorized ops, index, and recycle.
dplyr
Chain mutate, filter, group_by, summarise, and joins with the native pipe.
Statistics
Compute summaries, run t-tests, linear models, ANOVA, and use distributions.
Apply Family
Apply functions over arrays, lists, and groups with apply, lapply, sapply, tapply.
Data Import/Export
Read and write CSV, TSV, RDS, RData, and text files with base R.