Data Visualization in R Using ggplot2 - Module 1
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ ggplot2 3.5.1 ✔ tibble 3.2.1
✔ lubridate 1.9.3 ✔ tidyr 1.3.1
✔ purrr 1.0.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
data(PlantGrowth)
str(PlantGrowth)
'data.frame': 30 obs. of 2 variables:
$ weight: num 4.17 5.58 5.18 6.11 4.5 4.61 5.17 4.53 5.33 5.14 ...
$ group : Factor w/ 3 levels "ctrl","trt1",..: 1 1 1 1 1 1 1 1 1 1 ...
plot(density(PlantGrowth$weight)) # Density plot using base R
ggplot(data = PlantGrowth,
aes(x = weight,
color = group)) +
geom_density()
ggplot(data = PlantGrowth,
aes(x = weight,
fill = group)) +
geom_density()
ggplot(data = PlantGrowth,
aes(x = weight,
fill = group)) +
geom_density(alpha = 0.3)
PlantGrowth_grouped <- PlantGrowth %>% # Group data using dplyr
group_by(group) %>%
summarize(mean_weight = mean(weight))
PlantGrowth_grouped
# A tibble: 3 × 2
group mean_weight
<fct> <dbl>
1 ctrl 5.03
2 trt1 4.66
3 trt2 5.53
ggplot(data = PlantGrowth_grouped, # ggplot2 bar chart
aes(x = group,
y = mean_weight)) +
geom_col()
PlantGrowth %>% # Manipulation & visualization
group_by(group) %>%
summarize(mean_weight = mean(weight)) %>%
ggplot(aes(x = group,
y = mean_weight)) +
geom_col()