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
andfrom
to define the edges, in text labelst
for what time the note plays for the animationthe 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
from | to | t | note |
---|---|---|---|
<chr> | <chr> | <dbl> | <dbl> |
D | D | 0.0 | 62 |
D | A | 1.2 | 62 |
A | F | 2.4 | 69 |
F | D | 3.6 | 65 |
D | C# | 4.8 | 62 |
C# | D | 6.0 | 61 |
D | E | 6.6 | 62 |
E | F | 7.2 | 64 |
F | G | 8.7 | 65 |
G | F | 9.0 | 67 |
F | E | 9.3 | 65 |
E | D | 9.6 | 64 |
D | D | 10.2 | 62 |
# 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