tidygraph graph of notes

tidygraph graph of notes#

Mathematically, a graph is a set of nodes, and a set of pairs of the nodes defining where the edges are.

With the melody in a dataframe, a tidygraph object can be obtained. To convert it into a graph object that could be animated and laid out in the order the notes appear in the melody, I needed four things.

  • to and from to define the edges, in text labels

  • t for what time the note plays for the animation

  • the note as number so the layout reflected the order of notes

# get melody dataframe
melody_df <- readRDS(url('https://github.com/softloud/digmus/raw/main/outputs/step-output/melody_df.rds'))

suppressMessages(library(tidyverse))
melody_graphable <- melody_df %>%
  arrange(on) %>%
  mutate(
    from = note_name,
    to = lead(note_name),
    t = off
  ) %>%
  dplyr::filter(!is.na(to)) %>%
  select(from, to, t, note) %>%
  # get start note
  rbind(
    melody_df %>%
      mutate(
        from = note_name,
        to = note_name,
        t = 0
      ) %>%
      select(from, to, t, note) %>%
      slice(1)
  ) %>%
  # get end note
  rbind(
    melody_df %>%
      mutate(
        from = note_name,
        to = note_name,
        t = off
      ) %>%
      select(from, to, t, note) %>%
      slice(n())
  ) %>%
  arrange(t) 

# inspect
melody_graphable
A tibble: 13 × 4
fromtotnote
<chr><chr><dbl><dbl>
D D 0.062
D A 1.262
A F 2.469
F D 3.665
D C# 4.862
C#D 6.061
D E 6.662
E F 7.264
F G 8.765
G F 9.067
F E 9.365
E D 9.664
D D 10.262
# convert to graph object
suppressMessages(library(tidygraph))


melody_graphable %>%
    arrange(note) %>%
    as_tbl_graph()
# A tbl_graph: 6 nodes and 13 edges
#
# A directed multigraph with 1 component
#
# Node Data: 6 × 1 (active)
  name 
  <chr>
1 C#   
2 D    
3 E    
4 F    
5 G    
6 A    
#
# Edge Data: 13 × 4
   from    to     t  note
  <int> <int> <dbl> <dbl>
1     1     2   6      61
2     2     2   0      62
3     2     6   1.2    62
# ℹ 10 more rows