Skip to content

visualizations

Charting and network-visualization helpers (Altair, Plotly, pyvis) built on top of ngram, cadence, and presentation-type results from main_objs.py.

The ready-made chart functions (cadence_radar through plot_species_cadences) each take the result of a single piece or a whole corpus: run the method on piece or corpus, then pass the result to the chart function, for example cadence_radar(corpus.cadences()). Each returns a Plotly figure. See the Visualizations tutorial for worked examples.

This script contains the method

NgramColorManager

Generates visually distinct color palettes for ngram/pattern charts.

Uses a curated 12-color qualitative palette (Paul Tol's) for up to 12 colors, then extends with golden-ratio HSV sampling for any additional colors needed.

CURATED_12 class-attribute

CURATED_12 = ['#4477AA', '#CC6677', '#228833', '#DDCC77', '#AA3377', '#66CCEE', '#EE6633', '#BBBBBB', '#117733', '#332288', '#882255', '#44AA99']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

generate_distinct_colors

generate_distinct_colors(n)

Return n distinct colors.

Uses the curated 12-color palette for the first 12 entries, then extends with golden-ratio HSV sampling for any additional colors needed.

Source code in crim_intervals/visualizations.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def generate_distinct_colors(self, n):
    """Return n distinct colors.

    Uses the curated 12-color palette for the first 12 entries, then
    extends with golden-ratio HSV sampling for any additional colors needed.
    """
    colors = list(self.CURATED_12[:n])
    if n > len(self.CURATED_12):
        golden_ratio_conjugate = 0.618033988749895
        h = 0.1
        for _ in range(n - len(self.CURATED_12)):
            h = (h + golden_ratio_conjugate) % 1.0
            # Alternate saturation between two levels to aid distinction
            s = 0.85 if len(colors) % 2 == 0 else 0.55
            v = 0.90
            colors.append(mplt.colors.to_hex(mplt.colors.hsv_to_rgb([h, s, v])))
    return colors

ColorManager

ColorManager()

Assigns and caches a consistent color per pattern across a session.

The first time a pattern string is seen it is assigned a color (via NgramColorManager's palette generator); subsequent lookups for the same pattern return the same color, so a pattern keeps its color across multiple charts.

Source code in crim_intervals/visualizations.py
 98
 99
100
101
102
def __init__(self):
    self.pattern_colors = {}
    # Use the advanced color generator from NgramColorManager
    self.ngram_color_manager = NgramColorManager()
    self.color_index = 0

assign_colors_to_dataframe

assign_colors_to_dataframe(df)

Assign colors to dataframe patterns

Source code in crim_intervals/visualizations.py
138
139
140
141
142
def assign_colors_to_dataframe(self, df):
    """Assign colors to dataframe patterns"""
    df = df.copy()
    df['color'] = df['pattern'].apply(self.get_color_for_pattern)
    return df

get_color_for_pattern

get_color_for_pattern(pattern_str)

Get or assign a color for a pattern

Source code in crim_intervals/visualizations.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def get_color_for_pattern(self, pattern_str):
    """Get or assign a color for a pattern"""
    if pattern_str not in self.pattern_colors:
        # Get all unique patterns we need colors for
        all_patterns = list(self.pattern_colors.keys()) + [pattern_str]
        n_colors_needed = len(all_patterns)

        # Generate enough colors using the advanced color generator
        colors = self.ngram_color_manager.generate_distinct_colors(n_colors_needed)

        # Assign the new color to the new pattern
        self.pattern_colors[pattern_str] = colors[-1]

    return self.pattern_colors[pattern_str]

pre_register_patterns

pre_register_patterns(patterns)

Pre-register patterns with the color manager to ensure consistency.

Args: patterns: List of patterns (tuples, lists, or strings) to register

Source code in crim_intervals/visualizations.py
109
110
111
112
113
114
115
116
117
118
119
120
121
def pre_register_patterns(self, patterns):
    """
    Pre-register patterns with the color manager to ensure consistency.

    Args:
        patterns: List of patterns (tuples, lists, or strings) to register
    """
    for pattern in patterns:
        if isinstance(pattern, (list, tuple)):
            pattern_str = ", ".join(str(item) for item in pattern)
        else:
            pattern_str = str(pattern)
        self.get_color_for_pattern(pattern_str)

reset

reset()

Reset the color manager state

Source code in crim_intervals/visualizations.py
104
105
106
107
def reset(self):
    """Reset the color manager state"""
    self.pattern_colors = {}
    self.color_index = 0

PatternStyleManager

PatternStyleManager()

Assigns each unique pattern a distinct combination of a hatch shape and a grey shade, as a print/colorblind-safe alternative to ColorManager's color-based distinction. Shades are light-to-medium so a black hatch always reads clearly on top of them, and shape/shade are cycled with coprime step sizes so consecutive patterns don't repeat the same shade.

Source code in crim_intervals/visualizations.py
160
161
def __init__(self):
    self.pattern_styles = {}

GREY_SHADES class-attribute

GREY_SHADES = ['#e0e0e0', '#b8b8b8', '#8f8f8f', '#666666', '#cfcfcf', '#a3a3a3']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

HATCH_SHAPES class-attribute

HATCH_SHAPES = ['/', '\\', 'x', '-', '|', '+', '.']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

get_style_for_pattern

get_style_for_pattern(pattern_str)

Get or assign a hatch shape + grey shade combination for a pattern

Source code in crim_intervals/visualizations.py
167
168
169
170
171
172
173
174
def get_style_for_pattern(self, pattern_str):
    """Get or assign a hatch shape + grey shade combination for a pattern"""
    if pattern_str not in self.pattern_styles:
        index = len(self.pattern_styles)
        shape = self.HATCH_SHAPES[index % len(self.HATCH_SHAPES)]
        shade = self.GREY_SHADES[index % len(self.GREY_SHADES)]
        self.pattern_styles[pattern_str] = {'shape': shape, 'color': shade}
    return self.pattern_styles[pattern_str]

reset

reset()

Reset the pattern style manager state

Source code in crim_intervals/visualizations.py
163
164
165
def reset(self):
    """Reset the pattern style manager state"""
    self.pattern_styles = {}

create_bar_chart

create_bar_chart(variable, count, color, data, condition, *selectors)

Create a bar chart using Altair.

Source code in crim_intervals/visualizations.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def create_bar_chart(variable, count, color, data, condition, *selectors):
    """
    Create a bar chart using Altair.
    """
    color_scale = alt.Scale(
        domain=data['pattern'].unique(),
        range=data['color'].unique()
    )

    observer_chart = alt.Chart(data).mark_bar().encode(
        x=variable,
        y=count,
        color=alt.Color('pattern:N', scale=color_scale, legend=alt.Legend(title='Pattern')),
        opacity=alt.condition(condition, alt.value(1), alt.value(0.2))
    ).add_params(
        *selectors
    )
    return observer_chart

create_heatmap

create_heatmap(x, x2, y, color, data, heat_map_width, heat_map_height, selector_condition, *selectors, tooltip, style='color', style_manager=None)

Create a heatmap. By default (style='color') this is an interactive Altair chart that distinguishes segments by color. Pass style='greyscale' to get a Plotly chart that instead distinguishes segments using grey shades combined with hatch fills, for print or colorblind-safe use. The greyscale style does not support the Altair cross-filtering selection behavior.

If data has an 'entry' column (see process_ngrams_df's entry_mask), entries are drawn solid with an outline and other bars are faded.

Source code in crim_intervals/visualizations.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def create_heatmap(x, x2, y, color, data, heat_map_width, heat_map_height, selector_condition, *selectors, tooltip, style='color',
                   style_manager=None):
    """
    Create a heatmap. By default (style='color') this is an interactive Altair
    chart that distinguishes segments by color. Pass style='greyscale' to get a
    Plotly chart that instead distinguishes segments using grey shades combined
    with hatch fills, for print or colorblind-safe use. The greyscale style does
    not support the Altair cross-filtering selection behavior.

    If `data` has an 'entry' column (see process_ngrams_df's entry_mask),
    entries are drawn solid with an outline and other bars are faded.
    """
    if style == 'greyscale':
        return _create_greyscale_heatmap(x, x2, y, data, heat_map_width, heat_map_height, tooltip,
                                         style_manager=style_manager)

    color_scale = alt.Scale(
        domain=data['pattern'].unique(),
        range=data['color'].unique()
    )

    if 'entry' in data.columns:
        data = data.assign(opacity=data['entry'].map({True: 1.0, False: NON_ENTRY_OPACITY}))
        mark = alt.Chart(data).mark_bar(stroke='black')
        extra = dict(
            opacity=alt.condition(selector_condition, alt.Opacity('opacity:Q', scale=None, legend=None), alt.value(0.1)),
            strokeWidth=alt.condition('datum.entry', alt.value(1.5), alt.value(0)),
        )
    else:
        mark = alt.Chart(data).mark_bar()
        extra = dict(opacity=alt.condition(selector_condition, alt.value(1), alt.value(0.2)))

    heatmap = mark.encode(
        x=x,
        x2=x2,
        y=y,
        # symbolOpacity keeps legend swatches solid when bars are faded
        color=alt.Color('pattern:N', scale=color_scale, legend=alt.Legend(title='Pattern', symbolOpacity=1)),
        tooltip=tooltip,
        **extra
    ).properties(
        width=heat_map_width,
        height=heat_map_height
    ).add_params(
        *selectors
    )
    return heatmap

process_ngrams_df

process_ngrams_df(ngrams_df, ngrams_duration=None, selected_pattern=None, voices=None, entry_mask=None)

This method combines ngrams from all voices in different columns into one column and calculates the starts and end points of the patterns.

Durations are matched to n-grams by offset and voice (not by row position), so ngrams_duration may cover more cells than ngrams_df. N-grams with no matching duration get no end point and are left out of the heatmap, with a warning.

If entry_mask (a DataFrame with the same offsets and voices, e.g. the result of entries(..., anywhere=False)) is given, an 'entry' column is added: True where entry_mask has a value at that offset and voice.

Source code in crim_intervals/visualizations.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def process_ngrams_df(ngrams_df, ngrams_duration=None, selected_pattern=None, voices=None, entry_mask=None):
    """
    This method combines ngrams from all voices in different columns
    into one column and calculates the starts and end points of the
    patterns.

    Durations are matched to n-grams by offset and voice (not by row
    position), so `ngrams_duration` may cover more cells than `ngrams_df`.
    N-grams with no matching duration get no end point and are left out of
    the heatmap, with a warning.

    If `entry_mask` (a DataFrame with the same offsets and voices, e.g. the
    result of `entries(..., anywhere=False)`) is given, an 'entry' column is
    added: True where `entry_mask` has a value at that offset and voice.
    """
    ngrams_df = _process_ngrams_df_helper(ngrams_df, 'pattern')
    if entry_mask is not None:
        flags = _process_ngrams_df_helper(entry_mask, 'flag').dropna(subset=['flag'])
        flags = flags[flags['flag'] != '']   # entries(...).fillna('') leaves '' cells
        keys = pd.MultiIndex.from_frame(flags[['start', 'voice']])
        ngrams_df['entry'] = pd.MultiIndex.from_frame(ngrams_df[['start', 'voice']]).isin(keys)
    if ngrams_duration is not None:
        durations = _process_ngrams_df_helper(ngrams_duration, 'duration')
        durations = durations.dropna(subset=['duration']).drop_duplicates(['start', 'voice'])
        ngrams_df = ngrams_df.merge(durations, on=['start', 'voice'], how='left')
        ngrams_df['end'] = ngrams_df['start'] + ngrams_df.pop('duration').astype(float)
        unmatched = ngrams_df['pattern'].notna() & ngrams_df['end'].isna()
        if unmatched.any():
            warnings.warn(f"{unmatched.sum()} n-gram(s) have no matching duration in ngrams_duration "
                          "(same offset and voice) and will not be plotted. Make the durations with "
                          "piece.durations(df=..., n=..., mask_df=ngrams_df).")
    else:
        # make end=start+1 just to display offsets
        ngrams_df['end'] = ngrams_df['start'] + 1

    # filter according to voices and patterns (after computing durations for correct offsets)
    if voices:
        voice_condition = ngrams_df['voice'].isin(voices)
        ngrams_df = ngrams_df[voice_condition].dropna(how='all')
    if selected_pattern:
        pattern_condition = ngrams_df['pattern'].isin(selected_pattern)
        ngrams_df = ngrams_df[pattern_condition].dropna(how='all')
    return ngrams_df

generate_distinct_colors

generate_distinct_colors(n)

Generate n distinct colors using the HSV color space

Source code in crim_intervals/visualizations.py
404
405
406
407
408
409
410
411
412
413
def generate_distinct_colors(n):
    """Generate `n` distinct colors using the HSV color space"""
    colors = []
    for i in range(n):
        hue = i / n
        saturation = 0.65  # Fixed saturation
        value = 0.9  # Fixed value
        color = mplt.colors.to_hex(mplt.colors.hsv_to_rgb((hue, saturation, value)))
        colors.append(color)
    return colors

ngrams_color_helper

ngrams_color_helper(new_processed_ngrams_df: DataFrame, manager=None) -> DataFrame

Add a Series to the dataframe that assigns a unique hex color to each unique pattern using manager (a ColorManager), or the module's shared color_manager if None, to ensure consistency across plots.

Source code in crim_intervals/visualizations.py
415
416
417
418
419
420
421
def ngrams_color_helper(new_processed_ngrams_df: pd.DataFrame, manager=None) -> pd.DataFrame:
    """
    Add a Series to the dataframe that assigns a unique hex color to each unique pattern
    using `manager` (a ColorManager), or the module's shared color_manager if None,
    to ensure consistency across plots.
    """
    return (manager or _shared_color_manager).assign_colors_to_dataframe(new_processed_ngrams_df)

plot_ngrams_heatmap

plot_ngrams_heatmap(ngrams_df, ngrams_duration=None, selected_patterns=[], voices=[], heatmap_width=800, heatmap_height=300, includeCount=False, title=None, style='color', entry_mask=None, entries='mark', color_manager=None, style_manager=None)

Plot a heatmap for crim-intervals getNgram's output. Pass style='greyscale' for a hatch-patterned, grey-shaded Plotly chart instead of the default color-coded Altair chart (see create_heatmap).

The settings used to make the n-grams (recorded on ngrams_df by melodic/harmonic/ngrams, see get_settings) and the patterns and voices selected here are shown below the title.

ngrams_duration (optional) gives each bar its length. Make it with piece.durations(df=mel, n=n, mask_df=ngrams_df), using the same df and n as the n-grams. Durations are matched by offset and voice; any n-gram without one is left out, with a warning.

entry_mask (optional) marks which bars are real entries, which matters when ngrams_df comes from entries(..., anywhere=True) or ngrams(): those include occurrences that don't follow a rest. Pass the same call with anywhere=False, e.g.

ent = piece.entries(df=mel, n=4, thematic=True, anywhere=True)
real = piece.entries(df=mel, n=4, thematic=True, anywhere=False)
dur = piece.durations(df=mel, n=4, mask_df=ent)
viz.plot_ngrams_heatmap(ent, dur, entry_mask=real)

entries sets how entry_mask is used:

  • 'mark' (default): show every bar; entries are drawn solid with an outline and the other bars are faded.
  • 'only': show only the entries (the cells of entry_mask).
  • 'all': show every bar solid, with no marking (as if no entry_mask).

color_manager (a ColorManager) and style_manager (a PatternStyleManager, for style='greyscale') set the pattern colors. By default the module's shared managers are used, so a pattern keeps its color across charts. Pass your own to keep charts independent, or to give a group of charts the same colors (see plot_paired_ngram_heatmaps).

Source code in crim_intervals/visualizations.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def plot_ngrams_heatmap(ngrams_df, ngrams_duration=None, selected_patterns=[], voices=[],
                       heatmap_width=800, heatmap_height=300, includeCount=False, title=None, style='color',
                       entry_mask=None, entries='mark', color_manager=None, style_manager=None):
    """
    Plot a heatmap for crim-intervals getNgram's output. Pass style='greyscale'
    for a hatch-patterned, grey-shaded Plotly chart instead of the default
    color-coded Altair chart (see create_heatmap).

    The settings used to make the n-grams (recorded on `ngrams_df` by
    melodic/harmonic/ngrams, see `get_settings`) and the patterns and voices
    selected here are shown below the title.

    `ngrams_duration` (optional) gives each bar its length. Make it with
    `piece.durations(df=mel, n=n, mask_df=ngrams_df)`, using the same `df`
    and `n` as the n-grams. Durations are matched by offset and voice; any
    n-gram without one is left out, with a warning.

    `entry_mask` (optional) marks which bars are real entries, which matters
    when `ngrams_df` comes from `entries(..., anywhere=True)` or `ngrams()`:
    those include occurrences that don't follow a rest. Pass the same call
    with `anywhere=False`, e.g.

        ent = piece.entries(df=mel, n=4, thematic=True, anywhere=True)
        real = piece.entries(df=mel, n=4, thematic=True, anywhere=False)
        dur = piece.durations(df=mel, n=4, mask_df=ent)
        viz.plot_ngrams_heatmap(ent, dur, entry_mask=real)

    `entries` sets how `entry_mask` is used:

    - 'mark' (default): show every bar; entries are drawn solid with an
      outline and the other bars are faded.
    - 'only': show only the entries (the cells of `entry_mask`).
    - 'all': show every bar solid, with no marking (as if no `entry_mask`).

    `color_manager` (a `ColorManager`) and `style_manager` (a
    `PatternStyleManager`, for style='greyscale') set the pattern colors.
    By default the module's shared managers are used, so a pattern keeps its
    color across charts. Pass your own to keep charts independent, or to give
    a group of charts the same colors (see `plot_paired_ngram_heatmaps`).
    """
    ngrams_df, entry_mask = _apply_entries_option(ngrams_df, entry_mask, entries)
    processed_ngrams_df = process_ngrams_df(ngrams_df, ngrams_duration=ngrams_duration,
                                          selected_pattern=selected_patterns, voices=voices,
                                          entry_mask=entry_mask)
    extra = ['faded bars are not entries'] if entry_mask is not None else ()
    return _plot_ngrams_df_heatmap(processed_ngrams_df, heatmap_width=heatmap_width,
                                 heatmap_height=heatmap_height, includeCount=includeCount, title=title, style=style,
                                 settings=_ngram_chart_settings(ngrams_df, selected_patterns, voices, extra=extra),
                                 color_manager=color_manager, style_manager=style_manager)

plot_ngrams_barchart

plot_ngrams_barchart(ngrams_df, ngrams_duration=None, selected_patterns=[], voices=[], chart_width=800, chart_height=300, title=None, color_manager=None)

Plot a bar chart for crim-intervals getNgram's output. The settings used to make the n-grams, and the patterns and voices selected, are shown below the title. See plot_ngrams_heatmap for color_manager.

Source code in crim_intervals/visualizations.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
def plot_ngrams_barchart(ngrams_df, ngrams_duration=None, selected_patterns=[], voices=[], chart_width=800,
                        chart_height=300, title=None, color_manager=None):
    """
    Plot a bar chart for crim-intervals getNgram's output. The settings used
    to make the n-grams, and the patterns and voices selected, are shown below
    the title. See `plot_ngrams_heatmap` for `color_manager`.
    """
    processed_ngrams_df = process_ngrams_df(ngrams_df, ngrams_duration=ngrams_duration,
                                          selected_pattern=selected_patterns,
                                          voices=voices)
    chart = _plot_ngrams_df_barchart(processed_ngrams_df, chart_width=chart_width, chart_height=chart_height,
                                     color_manager=color_manager)
    alt_title = _altair_title(title, _ngram_chart_settings(ngrams_df, selected_patterns, voices))
    return chart.properties(title=alt_title) if alt_title is not None else chart

pre_register_patterns

pre_register_patterns(shared_entries, color_manager=None)

Pre-register patterns with a ColorManager (the module's shared one if None) so that they get the same colors in every chart.

Source code in crim_intervals/visualizations.py
625
626
627
628
629
630
def pre_register_patterns(shared_entries, color_manager=None):
    """Pre-register patterns with a ColorManager (the module's shared one if
    None) so that they get the same colors in every chart."""
    manager = color_manager or _shared_color_manager
    for pattern in shared_entries:
        manager.get_color_for_pattern(_pattern_str(pattern))

plot_comparison_heatmap

plot_comparison_heatmap(df, ema_col, main_category='musical_type', other_category='observer.name', option=1, heat_map_width=800, heat_map_height=300)

This method plots a chart for relationships/observations dataframe retrieved from their corresponding json files. This chart has two bar charts displaying the count of variables the users selected, and a heatmap displaying the locations of the relationship. :param df: relationships or observations dataframe :param ema_col: name of the ema column :param main_category: name of the main category for the first bar chart. The chart would be colored accordingly (default='musical_type'). :param other_category: name of the other category for the zeroth bar chart. (default='observer.name') :param heat_map_width: the width of the final heatmap (default=800) :param heat_map_height: the height of the final heatmap (default =300) :return: a big chart containing two smaller bar chart and a heatmap

Source code in crim_intervals/visualizations.py
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
def plot_comparison_heatmap(df, ema_col, main_category='musical_type', other_category='observer.name', option=1,
                            heat_map_width=800, heat_map_height=300):
    """
    This method plots a chart for relationships/observations dataframe retrieved from their
    corresponding json files. This chart has two bar charts displaying the count of variables
    the users selected, and a heatmap displaying the locations of the relationship.
    :param df: relationships or observations dataframe
    :param ema_col: name of the ema column
    :param main_category: name of the main category for the first bar chart.
    The chart would be colored accordingly (default='musical_type').
    :param other_category: name of the other category for the zeroth bar chart.
    (default='observer.name')
    :param heat_map_width: the width of the final heatmap (default=800)
    :param heat_map_height: the height of the final heatmap (default =300)
    :return: a big chart containing two smaller bar chart and a heatmap
    """

    df = df.copy()  # create a deep copy of the selected observations to protect the original dataframe
    df = _from_ema_to_offsets(df, ema_col)

    # sort by id
    df.sort_values(by=main_category, inplace=True)

    df = _from_ema_to_offsets(df, ema_col)
    df['website_url'] = _process_crim_json_url(df['url'])

    df['id'] = df['id'].astype(str)

    # because altair doesn't work when the categories' names have periods,
    # a period is replaced with a hyphen.

    new_other_category = other_category.replace(".", "_")
    new_main_category = main_category.replace(".", "_")

    df.rename(columns={other_category: new_other_category, main_category: new_main_category}, inplace=True)

    other_selector = alt.selection_point(fields=[new_other_category])
    main_selector = alt.selection_point(fields=[new_main_category])

    other_category = new_other_category
    main_category = new_main_category

    bar1 = create_bar_chart(main_category, str('count(' + main_category + ')'), main_category, df,
                            other_selector | main_selector, main_selector)
    bar0 = create_bar_chart(other_category, str('count(' + other_category + ')'), main_category, df,
                            other_selector | main_selector, other_selector)

    heatmap = alt.Chart(df).mark_bar().encode(
        x='start',
        x2='end',
        y='id',
        href='website_url',
        color=main_category,
        opacity=alt.condition(other_selector | main_selector, alt.value(1), alt.value(0.2)),
        tooltip=['website_url', main_category, other_category, 'start', 'end', 'id']
    ).properties(
        width=heat_map_width,
        height=heat_map_height
    ).add_params(
        main_selector
    ).interactive()

    chart = alt.vconcat(
        alt.hconcat(
            bar1,
            bar0
        ),
        heatmap
    )

    return chart

plot_close_match_heatmap

plot_close_match_heatmap(ngrams_df, key_pattern, ngrams_duration=None, selected_patterns=[], voices=[], heatmap_width=800, heatmap_height=300, title=None)

Plot how closely the other vectors match a selected vector. The settings used to make the n-grams and the key pattern are shown below the title. Uses the Levenshtein distance. :param ngrams_df: crim-intervals getNgram's output :param key_pattern: a pattern the users selected to compare other patterns with (tuple of floats) :param selected_pattern: the specific other vectors the users selected :param ngrams_duration: if None, simply output the offsets. If the users input a list of durations, caculate the end by adding durations with offsets and display the end on the heatmap accordingly. :param selected_patterns: list of specific patterns the users want (optional) :param voices: list of specific voices the users want (optional) :param heatmap_width: the width of the final heatmap (optional) :param heatmap_height: the height of the final heatmap (optional) :return: a bar chart that displays the different patterns and their counts, and a heatmap with the start offsets of chosen voices / patterns

Source code in crim_intervals/visualizations.py
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
def plot_close_match_heatmap(ngrams_df, key_pattern, ngrams_duration=None, selected_patterns=[], voices=[],
                             heatmap_width=800, heatmap_height=300, title=None):
    """
    Plot how closely the other vectors match a selected vector.
    The settings used to make the n-grams and the key pattern are shown below
    the title.
    Uses the Levenshtein distance.
    :param ngrams_df: crim-intervals getNgram's output
    :param key_pattern: a pattern the users selected to compare other patterns with (tuple of floats)
    :param selected_pattern: the specific other vectors the users selected
    :param ngrams_duration: if None, simply output the offsets. If the users input a
    list of durations, caculate the end by adding durations with offsets and
    display the end on the heatmap accordingly.
    :param selected_patterns: list of specific patterns the users want (optional)
    :param voices: list of specific voices the users want (optional)
    :param heatmap_width: the width of the final heatmap (optional)
    :param heatmap_height: the height of the final heatmap (optional)
    :return: a bar chart that displays the different patterns and their counts,
    and a heatmap with the start offsets of chosen voices / patterns
    """

    ngrams = process_ngrams_df(ngrams_df, ngrams_duration=ngrams_duration, selected_pattern=selected_patterns,
                               voices=voices)

    ngrams.dropna(subset=['pattern'], inplace=True)
    # dropping the NAs in pattern
    # calculate the score

    key_pattern = _close_match_helper(key_pattern)
    score_ngrams = _close_match(ngrams, key_pattern)

    slider = alt.binding_range(min=0, max=100, step=1, name='cutoff:')
    selector = alt.selection_single(name="SelectorName", fields=['cutoff'],
                                    bind=slider, init={'cutoff': 50})

    # sort voices
    if voices != None:
        if len(voices) == 0:
            voices = None
    y = alt.Y("voice", sort=voices)

    chart = create_heatmap('start', 'end', y, 'score', score_ngrams, heatmap_width, heatmap_height,
                           alt.datum.score > selector.cutoff, selector, tooltip=['start', 'end', 'pattern', 'score'])
    settings = _ngram_chart_settings(ngrams_df, selected_patterns, voices,
                                     extra=['compared with ' + ', '.join(str(x) for x in key_pattern)])
    return chart.properties(title=_altair_title(title or 'Close Matches', settings))

generate_ngrams_and_duration

generate_ngrams_and_duration(piece, df, n=3, exclude=['Rest'], interval_settings=('d', True, True), offsets='first')

This method accept a model and a dataframe with the melody or notes and rests and generate an ngram (in columnwise and unit=0 setting) and a corresponding duration ngram :param model: an Imported Piece object. :param df: dataframe containing consecutive notes. :param n: accept any positive integers and would output ngrams of the corresponding sizes can't handle the n=-1 option (refer to getNgrams documentation for more) :param exclude: (refer to getNgrams documentation) :param interval_settings: (refer to getNgrams documentation) :param offsets: (refer to getNgrams documentation) :return: ngram and corresponding duration dataframe!

Source code in crim_intervals/visualizations.py
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def generate_ngrams_and_duration(piece, df, n=3, exclude=['Rest'],
                                 interval_settings=('d', True, True), offsets='first'):
    """
    This method accept a model and a dataframe with the melody or notes
    and rests and generate an ngram (in columnwise and unit=0 setting)
    and a corresponding duration ngram
    :param model: an Imported Piece object.
    :param df: dataframe containing consecutive notes.
    :param n: accept any positive integers and would output ngrams of the corresponding sizes
    can't handle the n=-1 option (refer to getNgrams documentation for more)
    :param exclude: (refer to getNgrams documentation)
    :param interval_settings: (refer to getNgrams documentation)
    :param offsets: (refer to getNgrams documentation)
    :return: ngram and corresponding duration dataframe!
    """
    if n == -1:
        raise Exception("Cannot calculate the duration for this type of ngrams")

    # compute dur for the ngrams
    dur = piece.getDuration(df)
    dur = dur.reindex_like(df).map(str, na_action='ignore')
    # combine them and generate ngrams and duration at the same time
    notes_dur = pd.concat([df, dur])
    ngrams = piece.ngrams(df=df, n=n, exclude=exclude,
                             interval_settings=interval_settings, unit=0, offsets=offsets)
    dur_ngrams = piece.ngrams(df=dur, n=n, exclude=exclude,
                                 interval_settings=interval_settings, unit=0, offsets=offsets)
    dur_ngrams = dur_ngrams.reindex_like(ngrams)

    # sum up durations!
    dur_ngrams = dur_ngrams.map(lambda cell: sum([float(element) for element in cell]), na_action='ignore')

    return ngrams, dur_ngrams

process_network_df

process_network_df(df, interval_column_name, ema_column_name)

Create a small dataframe containing network

Source code in crim_intervals/visualizations.py
944
945
946
947
948
949
950
951
952
953
954
def process_network_df(df, interval_column_name, ema_column_name):
    """
    Create a small dataframe containing network
    """
    result_df = pd.DataFrame()
    result_df[['piece.piece_id', 'url', interval_column_name]] = \
        df[['piece.piece_id', 'url', interval_column_name]].copy()
    result_df[['segments']] = \
        df[ema_column_name].astype(str).str.split("/", 1, expand=True)[0]
    result_df['segments'] = result_df['segments'].str.split(",")
    return result_df

create_interval_networks

create_interval_networks(interval_column, interval_type)

Helper method to create networks for observations' intervals :param interval_column: column containing the intervals users want to examine :param interval_type: 'melodic' or 'time' :return: a dictionary of networks describing the intervals

Source code in crim_intervals/visualizations.py
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
def create_interval_networks(interval_column, interval_type):
    """
    Helper method to create networks for observations' intervals
    :param interval_column: column containing the intervals users want to
    examine
    :param interval_type: 'melodic' or 'time'
    :return: a dictionary of networks describing the intervals
    """
    # dictionary maps the first time/melodic interval to its corresponding
    # network
    networks_dict = {'all': Network(directed=True, notebook=True)}
    interval_column = interval_column.astype(str)
    networks_dict['all'].add_node('all', color='red', shape='circle', level=0)

    # create nodes from the patterns
    for node in interval_column:
        # create nodes according to the interval types
        if interval_type == 'melodic':
            nodes = re.sub(r'([+-])(?!$)', r'\1,', node).split(",")
            separator = ''
        elif interval_type == 'time':
            nodes = node.split("/")
            separator = '/'
        else:
            raise Exception("Please put either 'time' or 'melodic' for `type_interval`")

        # nodes would be grouped according to the first interval
        group = nodes[0]

        if not group in networks_dict:
            networks_dict[group] = Network(directed=True, notebook=True)

        prev_node = 'all'
        for i in range(1, len(nodes)):
            node_id = separator.join(node for node in nodes[:i])
            # add to its own family network
            networks_dict[group].add_node(node_id, group=group, physics=False, level=i)
            if prev_node != "all":
                networks_dict[group].add_edge(prev_node, node_id)

            # add to the big network
            networks_dict['all'].add_node(node_id, group=group, physics=False, level=i)
            networks_dict['all'].add_edge(prev_node, node_id)
            prev_node = node_id

    return networks_dict

cadence_radar

cadence_radar(cadences, groupby_column='Title', tone_ordering='Diatonic', limit_to_active=True, chart_title=None)

Radar plot of the relative distribution of cadence tones: for each group (piece, composer, ...), the percentage of its cadences on each tone.

Works with piece.cadences() or corpus.cadences().

Parameters:

Name Type Description Default
cadences DataFrame

Output of ImportedPiece.cadences or CorpusBase.cadences. Needs a 'Tone' column and the groupby_column.

required
groupby_column str, optional (default 'Title')

One polygon per value of this column, e.g. 'Title' or 'Composer'.

'Title'
tone_ordering str or list, optional (default 'Diatonic')

Order of tones around the circle: 'Diatonic', 'Fifths', 'Thirds', 'Chromatic' (see sorting_lists.cadence_tone_orders), or your own list (music21 spelling, e.g. 'B-'). Tones in the data but not in the order are added at the end.

'Diatonic'
limit_to_active bool, optional (default True)

If True, show only tones that occur in the data. If False, show every tone in the ordering.

True
chart_title str

A default naming the piece (for a single piece) is used if omitted.

None

Returns:

Type Description
Figure

Examples:

>>> cadence_radar(piece.cadences()).show()
>>> cadence_radar(corpus.cadences(), groupby_column='Composer', tone_ordering='Fifths')
Source code in crim_intervals/visualizations.py
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
def cadence_radar(cadences, groupby_column='Title', tone_ordering='Diatonic',
                  limit_to_active=True, chart_title=None):
    """
    Radar plot of the relative distribution of cadence tones: for each group
    (piece, composer, ...), the percentage of its cadences on each tone.

    Works with `piece.cadences()` or `corpus.cadences()`.

    Parameters
    ----------
    cadences : pandas.DataFrame
        Output of ImportedPiece.cadences or CorpusBase.cadences. Needs a
        'Tone' column and the `groupby_column`.
    groupby_column : str, optional (default 'Title')
        One polygon per value of this column, e.g. 'Title' or 'Composer'.
    tone_ordering : str or list, optional (default 'Diatonic')
        Order of tones around the circle: 'Diatonic', 'Fifths', 'Thirds',
        'Chromatic' (see `sorting_lists.cadence_tone_orders`), or your own list
        (music21 spelling, e.g. 'B-'). Tones in the data but not in the order
        are added at the end.
    limit_to_active : bool, optional (default True)
        If True, show only tones that occur in the data. If False, show every
        tone in the ordering.
    chart_title : str, optional
        A default naming the piece (for a single piece) is used if omitted.

    Returns
    -------
    plotly.graph_objects.Figure

    Examples
    --------
    >>> cadence_radar(piece.cadences()).show()
    >>> cadence_radar(corpus.cadences(), groupby_column='Composer', tone_ordering='Fifths')
    """
    if groupby_column not in cadences.columns:
        raise ValueError(f"cadences has no '{groupby_column}' column; "
                         f"choose one of {list(cadences.columns)}")
    order = cadence_tone_orders[tone_ordering] if isinstance(tone_ordering, str) else list(tone_ordering)
    cads = cadences.dropna(subset=['Tone'])
    if cads.empty:
        raise ValueError('No cadences with a Tone to plot.')

    grouped = cads.groupby([groupby_column, 'Tone']).size().rename('count')
    tones = _ordered_with_extras(order, cads['Tone'])
    if limit_to_active:
        tones = [t for t in tones if t in set(cads['Tone'])]
    groups = list(dict.fromkeys(cads[groupby_column]))
    # fill missing (group, tone) pairs with 0 so each polygon is complete
    full = pd.MultiIndex.from_product([groups, tones], names=[groupby_column, 'Tone'])
    grouped = grouped.reindex(full, fill_value=0).reset_index()
    totals = grouped.groupby(groupby_column)['count'].transform('sum')
    grouped['Percentage'] = (grouped['count'] / totals * 100).round(1)

    if chart_title is None:
        label = _piece_label(cadences)
        chart_title = f'Cadence Tones in {label}' if label else 'Cadence Tones'
    chart_title = _settings_title(chart_title, [
        f'{len(cads)} cadences',
        f'tone order: {tone_ordering}' if isinstance(tone_ordering, str) else 'custom tone order',
        'all tones' if not limit_to_active else None,
        f'grouped by {groupby_column}' if groupby_column != 'Title' else None,
        _n_pieces(cadences)])

    fig = px.line_polar(grouped, r='Percentage', theta='Tone', line_close=True,
                        color=groupby_column, markers=True,
                        hover_data={'count': True},
                        color_discrete_sequence=contrasting_colors,
                        category_orders={'Tone': tones, groupby_column: groups})
    fig.update_traces(fill='toself', line=dict(width=2))
    fig.update_layout(
        width=800, height=650,
        legend=dict(orientation='h', yanchor='top', y=-0.1, xanchor='center', x=0.5,
                    title=dict(text=groupby_column, side='top', font_size=12),
                    bordercolor='black', borderwidth=1, bgcolor='rgba(255,255,255,0.8)'),
        title=dict(text=chart_title, x=0.5),
        polar=dict(radialaxis=dict(visible=True, ticksuffix='%')),
        margin=dict(b=150, t=130),
        showlegend=len(groups) > 1)
    return fig

cadence_progress

cadence_progress(cadences, chart_title=None)

Scatter plot of cadences across the course of a piece: Progress (0 = start, 1 = end) on the x axis, cadence tone on the y axis, colored by cadence type.

Works with piece.cadences() or corpus.cadences(). For a corpus each piece gets its own row, since Progress is measured within each piece.

Parameters:

Name Type Description Default
cadences DataFrame

Output of ImportedPiece.cadences or CorpusBase.cadences. Needs 'Progress', 'Tone' and 'CadType' columns ('Title' for several pieces).

required
chart_title str

A default naming the piece (for a single piece) is used if omitted.

None

Returns:

Type Description
Figure

Examples:

>>> cadence_progress(piece.cadences()).show()
>>> cadence_progress(corpus.cadences()).show()   # one row per piece
Source code in crim_intervals/visualizations.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
def cadence_progress(cadences, chart_title=None):
    """
    Scatter plot of cadences across the course of a piece: Progress (0 = start,
    1 = end) on the x axis, cadence tone on the y axis, colored by cadence type.

    Works with `piece.cadences()` or `corpus.cadences()`. For a corpus each
    piece gets its own row, since Progress is measured within each piece.

    Parameters
    ----------
    cadences : pandas.DataFrame
        Output of ImportedPiece.cadences or CorpusBase.cadences. Needs
        'Progress', 'Tone' and 'CadType' columns ('Title' for several pieces).
    chart_title : str, optional
        A default naming the piece (for a single piece) is used if omitted.

    Returns
    -------
    plotly.graph_objects.Figure

    Examples
    --------
    >>> cadence_progress(piece.cadences()).show()
    >>> cadence_progress(corpus.cadences()).show()   # one row per piece
    """
    df = cadences.dropna(subset=['Tone']).copy()   # never alter the caller's data
    if df.empty:
        raise ValueError('No cadences with a Tone to plot.')
    tones = _ordered_with_extras(cadence_progress_tone_order, df['Tone'])
    tones = [t for t in tones if t in set(df['Tone'])]
    cad_types = _ordered_with_extras(cadence_type_order, df['CadType'])
    cad_types = [c for c in cad_types if c in set(df['CadType'])]
    n_titles = df['Title'].nunique() if 'Title' in df.columns else 1

    hover = {c: True for c in ['Composer', 'Title', 'Measure', 'Beat'] if c in df.columns}
    fig = px.scatter(df, x='Progress', y='Tone', color='CadType',
                     facet_row='Title' if n_titles > 1 else None,
                     facet_row_spacing=0.25 / n_titles if n_titles > 1 else None,
                     hover_data=hover,
                     color_discrete_map=cadence_type_colors,
                     category_orders={'Tone': tones, 'CadType': cad_types,
                                      'Title': list(dict.fromkeys(df['Title'])) if n_titles > 1 else []})
    fig.update_traces(marker=dict(size=18 if n_titles > 1 else 25, opacity=0.85,
                                  line=dict(width=1, color='white')))
    # categories run bottom-to-top in the order given (flats at the bottom)
    _category_yaxis(fig, tones, title='Tone')
    fig.update_xaxes(range=[-0.02, 1.02])

    if chart_title is None:
        label = _piece_label(df)
        chart_title = f'Progress of Cadences in {label}' if label else 'Progress of Cadences'
    chart_title = _settings_title(chart_title, [f'{len(df)} cadences', _n_pieces(df)])
    fig.update_layout(title=chart_title, width=900, height=500,
                      legend=dict(title_text='Cadence Type', orientation='v'))
    if n_titles > 1:
        fig.update_yaxes(title='')
        _facet_by_title(fig, n_titles, row_height=220)
    return fig

cadence_bar_chart

cadence_bar_chart(cadences, by='CadType', percent=True, groupby_column='Title', tone_ordering='Diatonic', chart_title=None)

Grouped bar chart of cadence types or cadence tones, one bar per group (piece, composer, ...) in each category.

Works with piece.cadences() or corpus.cadences().

Parameters:

Name Type Description Default
cadences DataFrame

Output of ImportedPiece.cadences or CorpusBase.cadences.

required
by str, optional (default 'CadType')

'CadType' for cadence types or 'Tone' for cadence tones. Evaded and abandoned cadences have no Tone, so they are counted for 'CadType' but left out (with a printed note) for 'Tone'.

'CadType'
percent bool, optional (default True)

True: each bar is a percentage of its group's cadences, so pieces of different lengths can be compared. False: raw counts.

True
groupby_column str, optional (default 'Title')

One bar color per value of this column, e.g. 'Title' or 'Composer'.

'Title'
tone_ordering str or list, optional (default 'Diatonic')

Order of tones on the x axis when by='Tone' (as in cadence_radar).

'Diatonic'
chart_title str

A default naming the piece (for a single piece) is used if omitted.

None

Returns:

Type Description
Figure

Examples:

>>> cadence_bar_chart(corpus.cadences()).show()
>>> cadence_bar_chart(corpus.cadences(), by='Tone', groupby_column='Composer')
Source code in crim_intervals/visualizations.py
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
def cadence_bar_chart(cadences, by='CadType', percent=True, groupby_column='Title',
                      tone_ordering='Diatonic', chart_title=None):
    """
    Grouped bar chart of cadence types or cadence tones, one bar per group
    (piece, composer, ...) in each category.

    Works with `piece.cadences()` or `corpus.cadences()`.

    Parameters
    ----------
    cadences : pandas.DataFrame
        Output of ImportedPiece.cadences or CorpusBase.cadences.
    by : str, optional (default 'CadType')
        'CadType' for cadence types or 'Tone' for cadence tones. Evaded and
        abandoned cadences have no Tone, so they are counted for 'CadType' but
        left out (with a printed note) for 'Tone'.
    percent : bool, optional (default True)
        True: each bar is a percentage of its group's cadences, so pieces of
        different lengths can be compared. False: raw counts.
    groupby_column : str, optional (default 'Title')
        One bar color per value of this column, e.g. 'Title' or 'Composer'.
    tone_ordering : str or list, optional (default 'Diatonic')
        Order of tones on the x axis when by='Tone' (as in `cadence_radar`).
    chart_title : str, optional
        A default naming the piece (for a single piece) is used if omitted.

    Returns
    -------
    plotly.graph_objects.Figure

    Examples
    --------
    >>> cadence_bar_chart(corpus.cadences()).show()
    >>> cadence_bar_chart(corpus.cadences(), by='Tone', groupby_column='Composer')
    """
    if by not in ('CadType', 'Tone'):
        raise ValueError("by must be 'CadType' or 'Tone'.")
    if groupby_column not in cadences.columns:
        raise ValueError(f"cadences has no '{groupby_column}' column; "
                         f"choose one of {list(cadences.columns)}")
    cads = cadences.dropna(subset=['CadType'])
    if by == 'Tone':
        missing = cads['Tone'].isna().sum()
        if missing:
            print(f'Note: {missing} cadence(s) without a Tone (evaded/abandoned) are not shown.')
        cads = cads.dropna(subset=['Tone'])
        order = cadence_tone_orders[tone_ordering] if isinstance(tone_ordering, str) else list(tone_ordering)
    else:
        order = cadence_type_order
    if cads.empty:
        raise ValueError('No cadences to plot.')

    categories = [c for c in _ordered_with_extras(order, cads[by]) if c in set(cads[by])]
    groups = list(dict.fromkeys(cads[groupby_column]))
    counts = cads.groupby([groupby_column, by]).size().rename('Count')
    full = pd.MultiIndex.from_product([groups, categories], names=[groupby_column, by])
    counts = counts.reindex(full, fill_value=0).reset_index()
    counts['Percentage'] = (counts['Count'] / counts.groupby(groupby_column)['Count'].transform('sum') * 100).round(1)
    y = 'Percentage' if percent else 'Count'

    single = len(groups) == 1
    label = _single_piece_label(cadences) if groupby_column == 'Title' else None
    if single and by == 'CadType':
        # one piece: color each bar by cadence type, as in cadence_progress
        fig = px.bar(counts, x=by, y=y, color=by, hover_data=['Count', 'Percentage'],
                     color_discrete_map=cadence_type_colors,
                     category_orders={by: categories})
    else:
        fig = px.bar(counts, x=by, y=y, color=groupby_column, barmode='group',
                     hover_data=['Count', 'Percentage'],
                     color_discrete_sequence=contrasting_colors,
                     category_orders={by: categories, groupby_column: groups})

    what = 'Cadence Types' if by == 'CadType' else 'Cadence Tones'
    if chart_title is None:
        chart_title = what + (f' in {label}' if label and single else f' by {groupby_column}')
    chart_title = _settings_title(chart_title, [
        'percent of each group\'s cadences' if percent else 'number of cadences',
        f'{len(cads)} cadences',
        (f'tone order: {tone_ordering}' if isinstance(tone_ordering, str) else 'custom tone order')
        if by == 'Tone' else None,
        _n_pieces(cadences)])
    fig.update_layout(title=chart_title, width=1000, height=550,
                      xaxis_title='Cadence Type' if by == 'CadType' else 'Tone',
                      yaxis_title='Percent of cadences' if percent else 'Number of cadences',
                      legend_title=groupby_column, showlegend=not single, bargap=0.2)
    if percent:
        fig.update_yaxes(ticksuffix='%')
    fig.update_xaxes(tickangle=-30 if by == 'CadType' else 0)
    return fig

radar_note_plot

radar_note_plot(weighted_notes_df, pitch_class_order='Fifths', exclude_rests=True, limit_to_active=True, color_grouping='title', chart_title=None)

Radar plot of how much of each piece's time is spent on each pitch class (duration-weighted), one polygon per piece (or per composer, final, ...).

Works with piece.note_weights() or corpus.note_weights().

Parameters:

Name Type Description Default
weighted_notes_df DataFrame

Output of ImportedPiece.note_weights or CorpusBase.note_weights (columns 'pitch_class', 'count', 'scaled', 'composer', 'title', ...).

required
pitch_class_order str or list, optional (default 'Fifths')

Order of pitch classes around the circle: 'Fifths', 'Diatonic', 'Chromatic' (see sorting_lists.note_pitch_class_orders), or your own list (music21 spelling, e.g. 'B-'). Pitch classes in the data but not in the order are added at the end.

'Fifths'
exclude_rests bool, optional (default True)

Leave out 'Rest' and show each pitch class as a share of sounding time.

True
limit_to_active bool, optional (default True)

If True, show only pitch classes that occur in the data. If False, show every pitch class in the ordering.

True
color_grouping str, optional (default 'title')

One polygon per value of this column, e.g. 'title', 'composer' or 'final'. Durations are summed within each group.

'title'
chart_title str

A default naming the piece (for a single piece) is used if omitted.

None

Returns:

Type Description
Figure

Examples:

>>> radar_note_plot(piece.note_weights()).show()
>>> radar_note_plot(corpus.note_weights(include_final=True), color_grouping='final')
Source code in crim_intervals/visualizations.py
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
def radar_note_plot(weighted_notes_df, pitch_class_order='Fifths', exclude_rests=True,
                    limit_to_active=True, color_grouping='title', chart_title=None):
    """
    Radar plot of how much of each piece's time is spent on each pitch class
    (duration-weighted), one polygon per piece (or per composer, final, ...).

    Works with `piece.note_weights()` or `corpus.note_weights()`.

    Parameters
    ----------
    weighted_notes_df : pandas.DataFrame
        Output of ImportedPiece.note_weights or CorpusBase.note_weights
        (columns 'pitch_class', 'count', 'scaled', 'composer', 'title', ...).
    pitch_class_order : str or list, optional (default 'Fifths')
        Order of pitch classes around the circle: 'Fifths', 'Diatonic',
        'Chromatic' (see `sorting_lists.note_pitch_class_orders`), or your own
        list (music21 spelling, e.g. 'B-'). Pitch classes in the data but not
        in the order are added at the end.
    exclude_rests : bool, optional (default True)
        Leave out 'Rest' and show each pitch class as a share of sounding time.
    limit_to_active : bool, optional (default True)
        If True, show only pitch classes that occur in the data. If False, show
        every pitch class in the ordering.
    color_grouping : str, optional (default 'title')
        One polygon per value of this column, e.g. 'title', 'composer' or
        'final'. Durations are summed within each group.
    chart_title : str, optional
        A default naming the piece (for a single piece) is used if omitted.

    Returns
    -------
    plotly.graph_objects.Figure

    Examples
    --------
    >>> radar_note_plot(piece.note_weights()).show()
    >>> radar_note_plot(corpus.note_weights(include_final=True), color_grouping='final')
    """
    df = weighted_notes_df.copy()
    df['pitch_class'] = df['pitch_class'].astype(str)
    if color_grouping not in df.columns:
        # accept 'Title' for 'title', etc. (note_weights uses lower-case names)
        matches = [c for c in df.columns if c.lower() == color_grouping.lower()]
        if not matches:
            raise ValueError(f"No '{color_grouping}' column; choose one of {list(df.columns)}")
        color_grouping = matches[0]
    if exclude_rests:
        df = df[df['pitch_class'] != 'Rest']
    df = df[df['count'] > 0]
    if df.empty:
        raise ValueError('No notes to plot.')

    order = (note_pitch_class_orders[pitch_class_order] if isinstance(pitch_class_order, str)
             else list(pitch_class_order))
    if not exclude_rests:
        order = order + ['Rest']
    pcs = _ordered_with_extras(order, df['pitch_class'])
    if limit_to_active:
        pcs = [p for p in pcs if p in set(df['pitch_class'])]
    groups = list(dict.fromkeys(df[color_grouping]))

    # sum durations per group and pitch class, fill gaps with 0 so every
    # polygon is complete, then take percentages within each group
    grouped = df.groupby([color_grouping, 'pitch_class'])['count'].sum()
    full = pd.MultiIndex.from_product([groups, pcs], names=[color_grouping, 'pitch_class'])
    grouped = grouped.reindex(full, fill_value=0).reset_index()
    totals = grouped.groupby(color_grouping)['count'].transform('sum')
    grouped['Percentage'] = (grouped['count'] / totals * 100).round(1)

    if chart_title is None:
        label = _piece_label(df, title_col='title', composer_col='composer')
        chart_title = f'Weighted Pitch Classes in {label}' if label else 'Weighted Pitch Classes'
    chart_title = _settings_title(chart_title, [
        (f'pitch-class order: {pitch_class_order}' if isinstance(pitch_class_order, str)
         else 'custom pitch-class order'),
        'rests excluded' if exclude_rests else 'rests included',
        'all pitch classes' if not limit_to_active else None,
        f'grouped by {color_grouping}' if color_grouping.lower() != 'title' else None,
        _n_pieces(df, title_col='title')])

    fig = px.line_polar(grouped, r='Percentage', theta='pitch_class', line_close=True,
                        color=color_grouping, markers=True,
                        hover_data={'count': ':.1f'},
                        labels={'pitch_class': 'Pitch class', 'count': 'Duration (quarter notes)'},
                        color_discrete_sequence=contrasting_colors,
                        category_orders={'pitch_class': pcs, color_grouping: groups})
    fig.update_traces(fill='toself', line=dict(width=2), opacity=0.8)
    fig.update_layout(
        width=800, height=650,
        legend=dict(orientation='h', yanchor='top', y=-0.1, xanchor='center', x=0.5,
                    title=dict(text=color_grouping.capitalize(), side='top', font_size=12),
                    bordercolor='black', borderwidth=1, bgcolor='rgba(255,255,255,0.8)'),
        title=dict(text=chart_title, x=0.5),
        polar=dict(radialaxis=dict(visible=True, ticksuffix='%')),
        margin=dict(b=150, t=130),
        showlegend=len(groups) > 1)
    return fig

voice_range_chart

voice_range_chart(voice_ranges_df, final=None, piece_order='mass', sort_voice='2', title=None)

Plot voice ranges (from piece.voice_ranges() or corpus.voice_ranges()) as horizontal bars, one row per piece and voice, with dotted reference lines at the modally significant pitches for the final.

Parameters:

Name Type Description Default
voice_ranges_df DataFrame

Output of ImportedPiece.voice_ranges or CorpusBase.voice_ranges.

required
final str

Plot only pieces with this final. If omitted and the data contain a single final, that final's reference lines are drawn; if they contain several, no reference lines are drawn.

None
piece_order str or list, optional (default 'mass')

How to order the pieces (top to bottom). Voices within each piece are always shown from highest staff (V1) down.

  • 'mass': models (titles without a Mass movement name) first, then Mass movements in liturgical order (Kyrie, Gloria, Credo, Sanctus, Agnus Dei); within each group, by sort_voice's lowest note.
  • 'range': by sort_voice's lowest note only, with no model/Mass grouping. Useful for pieces not related as model and Mass.
  • 'alpha': alphabetically by title.
  • 'given': the order in which titles first appear in voice_ranges_df, so you can sort the DataFrame yourself (e.g. by date or composer).
  • a list of titles: exactly that order. Titles not in the list are added at the end, in 'given' order, with a printed note.
'mass'
sort_voice str, optional (default '2')

The voice whose lowest note orders pieces for 'mass' and 'range'. Pieces without this voice fall back to their overall lowest note.

'2'
title str

Chart title. A default naming the final is used if omitted.

None

Returns:

Type Description
Figure

Call .show() to display it, or .write_html(path) to save it.

Examples:

voice_ranges_df = corpus.voice_ranges(top_n=7)
fig = voice_range_chart(voice_ranges_df, final='G')
fig.show()

# unrelated pieces, ordered by date (sort the DataFrame first)
# note you will need dates_df produced separately!
voice_ranges_df = voice_ranges_df.merge(dates_df, on='Title').sort_values('Date')
voice_range_chart(voice_ranges_df, piece_order='given').show()

# a custom order
voice_range_chart(voice_ranges_df, piece_order=['Veni speciosam', 'Je suis déshéritée'])
Source code in crim_intervals/visualizations.py
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
def voice_range_chart(voice_ranges_df, final=None, piece_order='mass', sort_voice='2', title=None):
    """
    Plot voice ranges (from `piece.voice_ranges()` or `corpus.voice_ranges()`)
    as horizontal bars, one row per piece and voice, with dotted reference
    lines at the modally significant pitches for the final.

    Parameters
    ----------
    voice_ranges_df : pandas.DataFrame
        Output of ImportedPiece.voice_ranges or CorpusBase.voice_ranges.
    final : str, optional
        Plot only pieces with this final. If omitted and the data contain a
        single final, that final's reference lines are drawn; if they contain
        several, no reference lines are drawn.
    piece_order : str or list, optional (default 'mass')
        How to order the pieces (top to bottom). Voices within each piece
        are always shown from highest staff (V1) down.

        * 'mass': models (titles without a Mass movement name) first, then
          Mass movements in liturgical order (Kyrie, Gloria, Credo, Sanctus,
          Agnus Dei); within each group, by `sort_voice`'s lowest note.
        * 'range': by `sort_voice`'s lowest note only, with no model/Mass
          grouping. Useful for pieces not related as model and Mass.
        * 'alpha': alphabetically by title.
        * 'given': the order in which titles first appear in `voice_ranges_df`,
          so you can sort the DataFrame yourself (e.g. by date or composer).
        * a list of titles: exactly that order. Titles not in the list are
          added at the end, in 'given' order, with a printed note.
    sort_voice : str, optional (default '2')
        The voice whose lowest note orders pieces for 'mass' and 'range'.
        Pieces without this voice fall back to their overall lowest note.
    title : str, optional
        Chart title. A default naming the final is used if omitted.

    Returns
    -------
    plotly.graph_objects.Figure
        Call `.show()` to display it, or `.write_html(path)` to save it.

    Examples
    --------
    ```python
    voice_ranges_df = corpus.voice_ranges(top_n=7)
    fig = voice_range_chart(voice_ranges_df, final='G')
    fig.show()

    # unrelated pieces, ordered by date (sort the DataFrame first)
    # note you will need dates_df produced separately!
    voice_ranges_df = voice_ranges_df.merge(dates_df, on='Title').sort_values('Date')
    voice_range_chart(voice_ranges_df, piece_order='given').show()

    # a custom order
    voice_range_chart(voice_ranges_df, piece_order=['Veni speciosam', 'Je suis déshéritée'])
    ```
    """
    df = voice_ranges_df.copy()
    if 'Title' not in df.columns:
        df['Title'] = ''
    df['Title'] = df['Title'].astype(str)
    df['Voice'] = df['Voice'].astype(str)
    if final is not None:
        df = df[df['Final'] == final]
    if df.empty:
        raise ValueError('No voice ranges to plot (check the `final` filter).')

    def ps(n):
        return m21_pitch.Pitch(n).ps

    df['Low_ps'] = df['LowestNote'].map(ps)
    df['Span'] = df['HighestNote'].map(ps) - df['Low_ps']

    def title_rank(t):
        # titles without a Mass movement name (e.g. models) sort first
        return next((i + 1 for i, m in enumerate(_MASS_MOVEMENTS) if m in t), 0)

    def anchor_low(t):
        rows = df[df['Title'] == t]
        anchor = rows[rows['Voice'] == str(sort_voice)]
        return (anchor if len(anchor) else rows)['Low_ps'].min()

    given = list(dict.fromkeys(df['Title']))      # first-appearance order
    if isinstance(piece_order, (list, tuple)):
        custom = [str(t) for t in piece_order]
        unknown = [t for t in custom if t not in given]
        if unknown:
            print('piece_order titles not in the data (ignored): {}'.format(', '.join(unknown)))
        rest = [t for t in given if t not in custom]
        if rest:
            print('Titles not in piece_order, added at the end: {}'.format(', '.join(rest)))
        titles = [t for t in custom if t in given] + rest
    elif piece_order == 'mass':
        titles = sorted(given, key=lambda t: (title_rank(t), anchor_low(t)))
    elif piece_order == 'range':
        titles = sorted(given, key=anchor_low)
    elif piece_order == 'alpha':
        titles = sorted(given)
    elif piece_order == 'given':
        titles = given
    else:
        raise ValueError("piece_order must be 'mass', 'range', 'alpha', 'given', or a list of titles.")

    def voice_key(v):
        return (0, int(v), v) if v.isdigit() else (1, 0, v)

    df['Title_Voice'] = (df['Title'] + '  [V' + df['Voice'] + ']').str.strip()
    labels = []
    for t in titles:
        for v in sorted(df.loc[df['Title'] == t, 'Voice'].unique(), key=voice_key):
            labels.append(f'{t}  [V{v}]'.strip())

    voices = sorted(df['Voice'].unique(), key=voice_key)
    palette = contrasting_colors
    fig = px.bar(df, x='Span', y='Title_Voice', base='Low_ps', orientation='h',
                 color='Voice', opacity=0.75,
                 color_discrete_map={v: palette[i % len(palette)] for i, v in enumerate(voices)},
                 category_orders={'Title_Voice': labels, 'Voice': voices},
                 hover_data={'Title': True, 'Voice': True, 'Range': True,
                             'Span': False, 'Low_ps': False, 'Title_Voice': False},
                 labels={'Title_Voice': 'Piece / Voice'})

    finals = df['Final'].dropna().unique() if 'Final' in df.columns else []
    the_final = finals[0] if len(finals) == 1 else None
    for point in _RANGE_REFERENCE_BY_FINAL.get(the_final, []):
        fig.add_vline(x=ps(point), line_dash='dot', line_color='gray', line_width=1,
                      annotation_text=point, annotation_position='top')

    lo = int(df['Low_ps'].min()) - 2
    hi = int((df['Low_ps'] + df['Span']).max()) + 2
    ticks = [p for p in range(lo, hi + 1) if m21_pitch.Pitch(ps=p).accidental is None]
    if title is None:
        title = (f'Voice Ranges in Pieces with Final {the_final}' if the_final
                 else 'Voice Ranges (several finals; filter by final for reference lines)')
    settings = [p for p in _data_settings(voice_ranges_df) if not p.startswith('final:')]
    title = _settings_title(title, settings + [
        f'final: {final}' if final is not None else None,
        {'mass': 'models, then Mass movements', 'range': 'pieces by range', 'alpha': 'pieces alphabetical',
         'given': 'pieces as given'}.get(piece_order, f'piece order: {piece_order}')
        if isinstance(piece_order, str) else 'custom piece order',
        _n_pieces(df)])
    fig.update_layout(
        title=title,
        xaxis=dict(title='Note Range', tickmode='array', tickvals=ticks,
                   ticktext=[m21_pitch.Pitch(ps=p).nameWithOctave for p in ticks],
                   tickangle=45),
        # set the order explicitly: px reverses category_orders for horizontal
        # bars, so combining it with autorange='reversed' alone would flip it
        yaxis=dict(title='', autorange='reversed',
                   categoryorder='array', categoryarray=labels),
        height=max(400, 28 * len(labels) + 180), width=1000,
        bargap=0.3, margin=dict(l=250, r=100, t=100, b=50))
    return fig

plot_species

plot_species(species_df, octave_order=['EbBbEb', 'BbFBb', 'FCF', 'CGC', 'GDG', 'DAD', 'AEA', 'EBE', 'BF#B'], show_voice_detail=True, progress_bins=5, chart_title=None)

Plot the octave species articulated by melodic leaps across the course of a piece (Progress 0 = start, 1 = end).

Works with piece.melodic_species() or corpus.melodic_species(). For a corpus each piece gets its own row, since Progress is measured within each piece.

Parameters:

Name Type Description Default
species_df DataFrame

Output of ImportedPiece.melodic_species or CorpusBase.melodic_species.

required
octave_order list of str, optional (default sorting_lists.species_octave_order)

Bottom-to-top order of octave species on the y axis. Octaves found in the data but not in the list are added at the end.

['EbBbEb', 'BbFBb', 'FCF', 'CGC', 'GDG', 'DAD', 'AEA', 'EBE', 'BF#B']
show_voice_detail bool, optional (default True)

True: one dot per interval, colored by voice. False: the piece is cut into progress_bins equal sections (e.g. 0–20%, 20–40%, ... of the piece) and each dot's size shows how many intervals articulate that octave in that section.

True
progress_bins int, optional (default 5)

Number of sections when show_voice_detail=False.

5
chart_title str

A default naming the piece (for a single piece) is used if omitted.

None

Returns:

Type Description
Figure

Examples:

>>> plot_species(piece.melodic_species()).show()
>>> plot_species(corpus.melodic_species(), show_voice_detail=False).show()
Source code in crim_intervals/visualizations.py
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
def plot_species(species_df, octave_order=species_octave_order, show_voice_detail=True,
                 progress_bins=5, chart_title=None):
    """
    Plot the octave species articulated by melodic leaps across the course of
    a piece (Progress 0 = start, 1 = end).

    Works with `piece.melodic_species()` or `corpus.melodic_species()`. For a
    corpus each piece gets its own row, since Progress is measured within each
    piece.

    Parameters
    ----------
    species_df : pandas.DataFrame
        Output of ImportedPiece.melodic_species or CorpusBase.melodic_species.
    octave_order : list of str, optional (default sorting_lists.species_octave_order)
        Bottom-to-top order of octave species on the y axis. Octaves found in
        the data but not in the list are added at the end.
    show_voice_detail : bool, optional (default True)
        True: one dot per interval, colored by voice. False: the piece is cut
        into `progress_bins` equal sections (e.g. 0–20%, 20–40%, ... of the
        piece) and each dot's size shows how many
        intervals articulate that octave in that section.
    progress_bins : int, optional (default 5)
        Number of sections when `show_voice_detail=False`.
    chart_title : str, optional
        A default naming the piece (for a single piece) is used if omitted.

    Returns
    -------
    plotly.graph_objects.Figure

    Examples
    --------
    >>> plot_species(piece.melodic_species()).show()
    >>> plot_species(corpus.melodic_species(), show_voice_detail=False).show()
    """
    df = _species_plot_df(species_df)
    octaves = [o for o in _ordered_with_extras(octave_order, df['Octave']) if o in set(df['Octave'])]
    n_titles = df['Title'].nunique() if 'Title' in df.columns else 1
    titles = list(dict.fromkeys(df['Title'])) if n_titles > 1 else []
    facet = dict(facet_row='Title' if n_titles > 1 else None,
                 facet_row_spacing=0.25 / n_titles if n_titles > 1 else None)

    if show_voice_detail:
        voices = sorted(df['Voice'].unique(), key=_voice_sort_key)
        hover = [c for c in ['Composer', 'Title', 'Measure', 'Beat', 'Interval', 'Species'] if c in df.columns]
        fig = px.scatter(df, x='Progress', y='Octave', color='Voice', hover_data=hover,
                         color_discrete_sequence=contrasting_colors,
                         category_orders={'Octave': octaves, 'Voice': voices, 'Title': titles},
                         **facet)
        fig.update_traces(marker=dict(size=12, opacity=0.8))
        fig.update_xaxes(range=[-0.02, 1.02])
        legend_title = 'Voice'
    else:
        # equal sections of the whole piece (0 to 1), labeled e.g. '0–20%'
        edges = np.linspace(0, 1, progress_bins + 1)
        sections = [f'{lo:.0%}–{hi:.0%}' for lo, hi in zip(edges[:-1], edges[1:])]
        df['Section'] = pd.cut(df['Progress'].clip(0, 1), bins=edges, labels=sections,
                               include_lowest=True)
        keys = (['Title'] if n_titles > 1 else []) + ['Section', 'Octave']
        counts = (df.groupby(keys, observed=True)
                    .agg(Count=('Interval', 'size'),
                         Intervals=('Interval', lambda s: ', '.join(sorted(s.unique()))),
                         Measures=('Measure', lambda s: ', '.join(str(int(m)) if float(m).is_integer() else str(m)
                                                                   for m in sorted(s.unique()))))
                    .reset_index())
        counts['Section'] = counts['Section'].astype(str)
        fig = px.scatter(counts, x='Section', y='Octave', size='Count', size_max=40,
                         hover_data=['Count', 'Intervals', 'Measures'],
                         color_discrete_sequence=contrasting_colors,
                         category_orders={'Octave': octaves, 'Section': sections, 'Title': titles},
                         **facet)
        fig.update_xaxes(categoryorder='array', categoryarray=sections, title_text=None)
        fig.update_layout(xaxis_title='Section of piece')   # bottom row only
        legend_title = None

    _category_yaxis(fig, octaves, title='Octave')
    if chart_title is None:
        label = _piece_label(df)
        chart_title = f'Melodic Species in {label}' if label else 'Melodic Species'
    chart_title = _settings_title(chart_title, _data_settings(species_df) + [
        'by voice' if show_voice_detail else f'{progress_bins} sections',
        f'{len(df)} leaps',
        _n_pieces(df)])
    fig.update_layout(title=chart_title, width=900, height=500, legend_title=legend_title)
    if n_titles > 1:
        fig.update_yaxes(title='')
        _facet_by_title(fig, n_titles, row_height=260)
    return fig

plot_species_cadences

plot_species_cadences(species_df, cadences_df, title=None, octave_order=['EbBbEb', 'BbFBb', 'FCF', 'CGC', 'GDG', 'DAD', 'AEA', 'EBE', 'BF#B'], chart_title=None)

Melodic species (colored by voice) and cadences (colored by cadence type) on a shared Progress axis, to compare where octave species and cadence tones fall in a piece.

Each piece gets two stacked panels: species above, cadences below. With corpus results (several Titles) every piece is stacked in one tall figure, two rows per piece, unless title names just one of them. For a large corpus the figure gets long: pass title=, or filter the DataFrames first, to plot fewer pieces.

Parameters:

Name Type Description Default
species_df DataFrame

Output of piece.melodic_species() or corpus.melodic_species().

required
cadences_df DataFrame

Output of piece.cadences() or corpus.cadences().

required
title str

Plot only this piece, when the DataFrames hold several (corpus results). If omitted, every piece in species_df is plotted.

None
octave_order list of str, optional (default sorting_lists.species_octave_order)

Bottom-to-top order of octave species in the species panels.

['EbBbEb', 'BbFBb', 'FCF', 'CGC', 'GDG', 'DAD', 'AEA', 'EBE', 'BF#B']
chart_title str

A default naming the piece (or 'Corpus') is used if omitted.

None

Returns:

Type Description
Figure

Examples:

>>> plot_species_cadences(piece.melodic_species(), piece.cadences()).show()
>>> species, cads = corpus.melodic_species(), corpus.cadences()
>>> plot_species_cadences(species, cads).show()          # every piece, stacked
>>> plot_species_cadences(species, cads, title=species['Title'].iloc[0]).show()
Source code in crim_intervals/visualizations.py
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
def plot_species_cadences(species_df, cadences_df, title=None, octave_order=species_octave_order,
                          chart_title=None):
    """
    Melodic species (colored by voice) and cadences (colored by cadence type)
    on a shared Progress axis, to compare where octave species and cadence
    tones fall in a piece.

    Each piece gets two stacked panels: species above, cadences below. With
    corpus results (several Titles) every piece is stacked in one tall
    figure, two rows per piece, unless `title` names just one of them. For a
    large corpus the figure gets long: pass `title=`, or filter the
    DataFrames first, to plot fewer pieces.

    Parameters
    ----------
    species_df : pandas.DataFrame
        Output of `piece.melodic_species()` or `corpus.melodic_species()`.
    cadences_df : pandas.DataFrame
        Output of `piece.cadences()` or `corpus.cadences()`.
    title : str, optional
        Plot only this piece, when the DataFrames hold several (corpus
        results). If omitted, every piece in `species_df` is plotted.
    octave_order : list of str, optional (default sorting_lists.species_octave_order)
        Bottom-to-top order of octave species in the species panels.
    chart_title : str, optional
        A default naming the piece (or 'Corpus') is used if omitted.

    Returns
    -------
    plotly.graph_objects.Figure

    Examples
    --------
    >>> plot_species_cadences(piece.melodic_species(), piece.cadences()).show()

    >>> species, cads = corpus.melodic_species(), corpus.cadences()
    >>> plot_species_cadences(species, cads).show()          # every piece, stacked
    >>> plot_species_cadences(species, cads, title=species['Title'].iloc[0]).show()
    """
    has_titles = 'Title' in species_df.columns and 'Title' in cadences_df.columns
    sp_all, cads_all = species_df, cadences_df
    if title is not None:
        if not has_titles:
            raise ValueError("title= needs a 'Title' column in both DataFrames.")
        sp_all = species_df[species_df['Title'] == title]
        cads_all = cadences_df[cadences_df['Title'] == title]
        if sp_all.empty:
            raise ValueError(f"No species_df rows for title {title!r}.")

    sp = _species_plot_df(sp_all)
    cads = cads_all.dropna(subset=['Tone'])

    # one (species, cadences) pair of rows per piece, in order of appearance
    if has_titles and sp['Title'].nunique() > 1:
        pieces = list(sp['Title'].dropna().unique())
        missing = set(cads['Title'].dropna()) - set(pieces)
        if missing:
            print('Titles with cadences but no species (not plotted): '
                  + ', '.join(map(repr, sorted(missing))))
        cads = cads[cads['Title'].isin(pieces)]
        parts = [(t, sp[sp['Title'] == t], cads[cads['Title'] == t]) for t in pieces]
    else:
        parts = [(None, sp, cads)]
    n = len(parts)

    # shared categories and colors, so every piece reads the same way
    octaves = [o for o in _ordered_with_extras(octave_order, sp['Octave']) if o in set(sp['Octave'])]
    tones = [t for t in _ordered_with_extras(cadence_progress_tone_order, cads['Tone']) if t in set(cads['Tone'])]
    voices = sorted(sp['Voice'].unique(), key=_voice_sort_key)
    voice_colors = {v: contrasting_colors[i % len(contrasting_colors)] for i, v in enumerate(voices)}
    cad_types = [c for c in _ordered_with_extras(cadence_type_order, cads['CadType']) if c in set(cads['CadType'])]

    if n == 1:
        subplot_titles = ('Melodic species by voice', 'Cadences by type')
    else:
        subplot_titles = []
        for t, sp_one, _ in parts:
            label = _single_piece_label(sp_one) or str(t)
            subplot_titles += [f'{label}: melodic species', f'{label}: cadences']
    fig = make_subplots(rows=2 * n, cols=1, vertical_spacing=min(0.1, 0.25 / n),
                        subplot_titles=subplot_titles)

    sp_hover = [c for c in ['Measure', 'Beat', 'Interval', 'Species'] if c in sp.columns]
    cad_hover = [c for c in ['Measure', 'Beat', 'CadType'] if c in cads.columns]
    shown = set()

    def _add(traces, row, kind, order, header, rank_base):
        # one legend entry per voice / cadence type (toggling it in every
        # piece), ranked so voices list first, then cadence types
        for trace in traces:
            key = (kind, trace.name)
            pos = order.index(trace.name) if trace.name in order else len(order)
            trace.update(legendgroup=f'{kind}:{trace.name}', showlegend=key not in shown,
                         legendrank=rank_base + pos)
            if key not in shown and pos == 0:
                trace.update(legendgrouptitle_text=header)
            shown.add(key)
            fig.add_trace(trace, row=row, col=1)

    for i, (_, sp_one, cads_one) in enumerate(parts):
        sp_row, cad_row = 2 * i + 1, 2 * i + 2
        fig_sp = px.scatter(sp_one, x='Progress', y='Octave', color='Voice', hover_data=sp_hover,
                            color_discrete_map=voice_colors,
                            category_orders={'Octave': octaves, 'Voice': voices})
        fig_sp.update_traces(marker=dict(size=11, opacity=0.8))
        _add(fig_sp.data, sp_row, 'voice', voices, 'Voice', 1)
        if not cads_one.empty:
            fig_cad = px.scatter(cads_one, x='Progress', y='Tone', color='CadType', hover_data=cad_hover,
                                 color_discrete_map=cadence_type_colors,
                                 category_orders={'Tone': tones, 'CadType': cad_types})
            fig_cad.update_traces(marker=dict(size=14, symbol='diamond', opacity=0.85,
                                              line=dict(width=1, color='white')))
            _add(fig_cad.data, cad_row, 'cadence', cad_types, 'Cadence Type', 1000)
        _category_yaxis(fig, octaves, title='Octave', row=sp_row, col=1)
        _category_yaxis(fig, tones, title='Tone', row=cad_row, col=1)
        fig.update_xaxes(title_text='Progress', row=cad_row, col=1)
    fig.update_xaxes(range=[-0.02, 1.02], matches='x')   # zoom all panels together
    fig.layout.xaxis.matches = None

    if chart_title is None:
        label = _piece_label(sp) or _piece_label(cads)
        chart_title = f'Melodic Species and Cadences in {label}' if label else 'Melodic Species and Cadences'
    chart_title = _settings_title(chart_title, _data_settings(species_df) + [
        f'{len(sp)} leaps', f'{len(cads)} cadences', _n_pieces(sp)])
    fig.update_layout(title=chart_title, height=700 if n == 1 else 150 + 560 * n, width=950,
                      legend=dict(x=1.02, y=1.0, xanchor='left', yanchor='top',
                                  groupclick='togglegroup', tracegroupgap=0),
                      margin=dict(r=220))
    return fig