Visualizing sorting algorithms step by step with ggplot2.
ggplot2
data-visualization
Author
Joshua Kunst
Published
September 25, 2015
Modified
August 13, 2026
Have you read Visualizing Algorithms by Mike Bostock? It’s a pure gold post. In that post Mike show a static representation of a sort algorithm and obvious it will fun to replicate that image with ggplot2 so here we go.
We need some sorts algorithms. In this link you can see some algorithms.
Every row is a step in sort the algorithm (a partial sort). This matrix is a hard to plot so we need a nicer structure. We can transform the matrix to a data_frame with the information of every position of every element in each step.
selection_sort_steps<-function(x=sample(1:15)){msteps<-matrix(data =x, ncol =length(x))for(iin1:(length(x)-1)){smallsub<-ifor(jin(i+1):(length(x)-0)){# Is not '- 1' like websiteif(x[j]<x[smallsub]){smallsub<-j}}temp<-x[i]x[i]<-x[smallsub]x[smallsub]<-tempmsteps<-rbind(msteps, as.vector(x))}msteps}
---title: "Visualizing sort algorithms with ggplot2"date: 2015-09-25description: "Visualizing sorting algorithms step by step with ggplot2."date-modified: 2026-08-13categories: [ggplot2, data-visualization]image: images/preview.png ---```{r setup, include=FALSE}knitr::opts_chunk$set(echo =TRUE)source(here::here("blog", "_R", "post_setup.R"))install_missing_packages(c("dplyr", "tidyr", "ggplot2", "viridis"))```Have you read [Visualizing Algorithms](http://bost.ocks.org/mike/algorithms/)by Mike Bostock? It's a *pure gold post*. In that post Mike show a *static* representation of a sort algorithm and obvious it will fun to replicate that imagewith ggplot2 so here we go.We need some sorts algorithms. In [this](http://faculty.cs.niu.edu/~hutchins/csci230/sorting.htm) link you cansee some algorithms. We start with Insertion sort:```{r}#| label: introduction-theme-setlibrary(dplyr)library(tidyr)library(ggplot2)library(viridis)theme_set(theme_void())insertion_sort_steps <-function(x =sample(1:15)){ msteps <-matrix(data = x, ncol =length(x))for (i in2:length(x)) { j <- iwhile ((j >1) && (x[j] < x[j -1])) { temp <- x[j] x[j] <- x[j -1] x[j -1] <- temp j <- j -1 msteps <-rbind(msteps, as.vector(x)) } } msteps}```Now to test it and see what the function do:```{r}#| label: introduction-set-seedset.seed(12345)x <-sample(seq(4))xmsteps <-insertion_sort_steps(x)as.data.frame(msteps)```Every *row* is a step in sort the algorithm (a partial sort). This matrix is a hard to plot so we need a nicer structure. We can transform the matrix to a *data_frame* with the information of every *position* of every *element* in each *step*. ```{r}#| label: introduction-define-sort-matix-to-dfsort_matix_to_df <-function(msteps){ df <-as.data.frame(msteps, row.names =NULL)names(df) <-seq(ncol(msteps)) df_steps <- df %>% tibble::as_tibble() %>%mutate(step =seq(nrow(.))) %>%gather(position, element, -step) %>%arrange(step) df_steps}```And we apply this function to the previous *steps matrix*.```{r}#| label: introduction-prepare-df-stepsdf_steps <-sort_matix_to_df(msteps)head(df_steps, 10)```The next step will be plot the data frame.```{r}#| label: introduction-define-plot-sortplot_sort <-function(df_steps, size =5, color.low ="#D1F0E1", color.high ="#524BB4"){ggplot(df_steps,aes(step, position, group = element, color = element, label = element)) +geom_path(size = size, alpha =1, lineend ="round") +scale_colour_gradient(low = color.low, high = color.high) +coord_flip() +scale_x_reverse() +theme(legend.position ="none")}```Now compare this:```{r}#| label: introduction-as-data-frameas.data.frame(msteps)```With:```{r}#| label: introduction-plot-sortplot_sort(df_steps, size =6) +geom_text(color ="white", size =4)```It works, so we can now scroll! ```{r fig.height=30}sample(seq(50)) %>%insertion_sort_steps() %>%sort_matix_to_df() %>%plot_sort(size =2.0)```Now try with other sort algorithms:Bubble sort:```{r}#| label: introduction-define-bubble-sort-stepsbubble_sort_steps <-function(x =sample(1:15)){ msteps <-matrix(data = x, ncol =length(x))for (i in1:(length(x) -1)) {for (j in1:(length(x) -1)) {if (x[j] > x[j +1]) { temp <- x[j] x[j] <- x[j +1] x[j +1] <- temp } msteps <-rbind(msteps, as.vector(x)) } } msteps}```Selection sort:```{r}#| label: introduction-define-selection-sort-stepsselection_sort_steps <-function(x =sample(1:15)){ msteps <-matrix(data = x, ncol =length(x))for (i in1:(length(x) -1)) { smallsub <- ifor (j in (i +1):(length(x) -0)) { # Is not '- 1' like websiteif (x[j] < x[smallsub]) { smallsub <- j } } temp <- x[i] x[i] <- x[smallsub] x[smallsub] <- temp msteps <-rbind(msteps, as.vector(x)) } msteps}```Now test with a longer vector:```{r}#| label: introduction-prepare-nn <-50x <-sample(seq(n))big_df <-rbind( x %>%selection_sort_steps() %>%sort_matix_to_df() %>%mutate(sort ="Selection Sort"), x %>%insertion_sort_steps() %>%sort_matix_to_df() %>%mutate(sort ="Insertion Sort"), x %>%bubble_sort_steps() %>%sort_matix_to_df() %>%mutate(sort ="Bubble Sort"))head(big_df)big_df %>%group_by(sort) %>%summarise(steps =n())``````{r fig.width=12, fig.height=10}ggplot( big_df,aes(step, position, group = element, color = element, label = element) ) +geom_path(size =0.8, alpha =1, lineend ="round") +scale_colour_gradient(low ="#c21500", high ="#ffc500") +# http://uigradients.com/#Kyotofacet_wrap(~sort, scales ="free_x", ncol =1) +theme(legend.position ="none",strip.background =element_rect(fill ="transparent", linetype =0),strip.text =element_text(size =8) )```Or we can plot vertically using the viridis palette from the [viridis package](https://github.com/sjmgarnier/viridis) : ```{r fig.width=12, fig.height=10}ggplot( big_df,aes(position, step, group = element, color = element, label = element) ) +geom_path(size =1, alpha =1, lineend ="round") +scale_colour_gradientn(colours =viridis_pal()(n)) +facet_wrap(~sort, scales ="free_y", nrow =1) +scale_y_reverse() +theme(legend.position ="none",strip.background =element_rect(fill ="transparent", linetype =0),strip.text =element_text(size =8) )```And that's it. If you write/implement another sort algorithm in this way let me know to view it ;). References:1. http://bost.ocks.org/mike/algorithms/1. http://faculty.cs.niu.edu/~hutchins/csci230/sorting.htm1. http://corte.si/posts/code/visualisingsorting/1. http://uigradients.com/#Kyoto1. http://algs4.cs.princeton.edu/21elementary/