Data Visualization with ggplot2
ggplot(data, aes(mappings)) + geom_*() + stat_*() + scale_*() + facet_*() + coord_*() + theme()
22.1 The grammar of graphics
ggplot(data, aes(mappings)) + geom_*() + stat_*() + scale_*() + facet_*() + coord_*() + theme()
library(ggplot2)
ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g, color = species)) +
geom_point(alpha = 0.7, size = 2) +
geom_smooth(method = "lm", se = FALSE) +
labs(title = "Penguin size", subtitle = "Palmer Station, Antarctica",
x = "Flipper length (mm)", y = "Body mass (g)", color = "Species",
caption = "Data: palmerpenguins") +
theme_minimal()22.2 Common geoms
geom_line(), geom_path(), geom_step() lines, time series geom_col() / geom_bar() bars (values / counts)
geom_histogram(), geom_density(), geom_freqpoly() geom_boxplot(), geom_violin(), geom_jitter() distributions by group geom_text(), geom_label() geom_tile(), geom_raster() geom_area(), geom_ribbon() areas, confidence bands geom_errorbar(), geom_pointrange()
geom_hline(), geom_vline(), geom_abline()
ggplot(penguins, aes(species, body_mass_g, fill = species)) +
geom_boxplot(show.legend = FALSE) + geom_jitter(width = 0.2, alpha = 0.3)
ggplot(penguins, aes(body_mass_g, fill = species)) + geom_density(alpha = 0.5)
ggplot(mpg, aes(class)) + geom_bar(aes(fill = drv), position = "dodge") # "stack", "fill"
ggplot(economics, aes(date, unemploy)) + geom_line(color = "firebrick")22.3 Facets, scales, coordinates, themes
p <- ggplot(mpg, aes(displ, hwy)) + geom_point()
p + facet_wrap(~ class, ncol = 4)
p + facet_grid(drv ~ cyl)
p + scale_x_log10() + scale_y_continuous(labels = scales::label_number(suffix = " mpg"))
p + aes(color = cty) + scale_color_viridis_c()
ggplot(mpg, aes(class, fill = drv)) + geom_bar() + scale_fill_brewer(palette = "Set2")
p + coord_flip(); p + coord_cartesian(xlim = c(2, 5)); ggplot(df, aes(x = "", y = n, fill = g)) + geom_col() + coord_polar("y")
p + theme_bw(base_size = 14) + theme(legend.position = "bottom", plot.title = element_text(face = "bold"))
theme_set(theme_light())
p + annotate("text", x = 6, y = 40, label = "outliers") + guides(color = "none")22.4 Saving & extending
Extensions: patchwork (p1 + p2 / p3 layouts), ggrepel (non-overlapping labels), gganimate (animation), plotly (ggplotly(p) interactive), ggthemes, ggridges, GGally (ggpairs), ggforce, ggiraph (interactive), esquisse (drag-and-drop builder), ggdist (uncertainty), scales (axis labels).
ggsave("plot.png", p, width = 8, height = 5, dpi = 300)22.5 Other visualization tools
plotly, highcharter, echarts4r, leaflet (maps), DT and reactable (interactive tables), gt and flextable (publication tables), visNetwork/ggraph (networks), corrplot, vcd (categorical), rayshader (3D).