Skip to content
R

ggplot2

Build layered plots with geoms, facets, and themes using the grammar of graphics.

By EZ4Code Team
ggplot2plot

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