music21.graph.primitives

Object definitions for graphing and plotting Stream objects.

The Graph object subclasses primitive, abstract fundamental graphing archetypes using the matplotlib library.

Graph

class music21.graph.primitives.Graph(*args, **keywords)

A music21.graph.primitives.Graph is an object that represents a visual graph or plot, automating the creation and configuration of this graph in matplotlib. It is a low-level object that most music21 users do not need to call directly; yet, as most graphs will take keyword arguments that specify the look of graphs, they are important to know about.

The keyword arguments can be provided for configuration are:

  • doneAction (see below)
  • alpha (which describes how transparent elements of the graph are)
  • dpi
  • colorBackgroundData
  • colorBackgroundFigure
  • colorGrid,
  • title (a string)
  • figureSize (a tuple of two ints)
  • colors (a list of colors to cycle through)
  • tickFontSize
  • tickColors (a dict of ‘x’: ‘#color’, ‘y’: ‘#color’)
  • titleFontSize
  • labelFontSize
  • fontFamily
  • hideXGrid
  • hideYGrid
  • xTickLabelRotation
  • marker
  • markersize

Graph objects do not manipulate Streams or other music21 data; they only manipulate raw data formatted for each Graph subclass, hence it is unlikely that users will call this class directly.

The doneAction argument determines what happens after the graph has been processed. Currently there are three options, ‘write’ creates a file on disk (this is the default), while ‘show’ opens an interactive GUI browser. The third option, None, does the processing but does not write any output.

figureSize:

A two-element iterable.

Scales all graph components but because of matplotlib limitations (esp. on 3d graphs) no all labels scale properly.

defaults to .figureSizeDefault

>>> a = graph.primitives.Graph(title='a graph of some data to be given soon', tickFontSize=9)
>>> a.data = [[0, 2], [1, 3]]
>>> a.graphType
'genericGraph'

Graph read/write properties

Graph.doneAction

returns or sets what should happen when the graph is created (see docs above) default is ‘write’.

Graph methods

Graph.applyFormatting(subplot)

Apply formatting to the Subplot (Axes) container and Figure instance.

ax should be an AxesSubplot object or an Axes3D object or something similar.

Graph.applyFormattingToOneAxis(subplot, axis)

Given a matplotlib.Axes object (a subplot) and a string of ‘x’, ‘y’, or ‘z’, set the Axes object’s xlim (or ylim or zlim or xlim3d, etc.) from self.axis[axis][‘range’], Set the label from self.axis[axis][‘label’], the scale, the ticks, and the ticklabels.

Returns the matplotlib Axis object that has been modified

Graph.applyGrid(subplot)

Apply the Grid to the subplot such that it goes below the data.

Graph.callDoneAction(fp=None)

Implement the desired doneAction, after data processing

static Graph.hideAxisSpines(subplot, leftBottom=False)

Remove the right and top spines from the diagram.

If leftBottom is True, remove the left and bottom spines as well.

Spines are removed by setting their colors to ‘none’ and every other tickline set_visible to False.

Graph.nextColor()

Utility function that cycles through the colors of self.colors...

>>> g = graph.primitives.Graph()
>>> g.colors
['#605c7f', '#5c7f60', '#715c7f']
>>> g.nextColor()
'#605c7f'
>>> g.nextColor()
'#5c7f60'
>>> g.nextColor()
'#715c7f'
>>> g.nextColor()
'#605c7f'
Graph.process()

Creates the figure and subplot, calls renderSubplot to get the subclass specific information on the data, runs hideAxisSpines, applyFormatting, and then calls the done action. Returns None, but the subplot is available at self.subplot

Graph.renderSubplot(subplot)

Calls the subclass specific information to get the data

Graph.setAxisLabel(axisKey, label, conditional=False)
Graph.setAxisRange(axisKey, valueRange, paddingFraction=0.1)

Set the range for the axis for a given axis key (generally, ‘x’, or ‘y’)

ValueRange is a two-element tuple of the lowest number and the highest.

By default there is a padding of 10% of the range in either direction. Set paddingFraction = 0 to eliminate this shift

Graph.setIntegerTicksFromData(unsortedData, axisKey='y', dataSteps=8)

Set the ticks for an axis (usually ‘y’) given unsorted data.

Data steps shows how many ticks to make from the data.

>>> g = graph.primitives.GraphHorizontalBar()
>>> g.setIntegerTicksFromData([10, 5, 3, 8, 20, 11], dataSteps=4)
>>> g.axis['y']['ticks']
([0, 5, 10, 15, 20], ['0', '5', '10', '15', '20'])

TODO: should this not also use min? instead of always starting from zero?

Graph.setTicks(axisKey, pairs)

Set the tick-labels for a given graph or plot’s axisKey (generally ‘x’, and ‘y’) with a set of pairs

Pairs are iterables of positions and labels.

N.B. – both ‘x’ and ‘y’ ticks have to be set in order to get matplotlib to display either... (and presumably ‘z’ for 3D graphs)

>>> g = graph.primitives.GraphHorizontalBar()
>>> g.axis['x']['ticks']
Traceback (most recent call last):
KeyError: 'ticks'
>>> g.axis['x']
{'range': None}
>>> g.setTicks('x', [(0, 'a'), (1, 'b')])
>>> g.axis['x']['ticks']
([0, 1], ['a', 'b'])
>>> g.setTicks('m', [('a', 'b')])
Traceback (most recent call last):
music21.graph.utilities.GraphException: Cannot find key 'm' in self.axis
>>> g.setTicks('x', [])
>>> g.axis['x']['ticks']
([], [])
Graph.show()

Calls the show() method of the matplotlib plot. For most matplotlib back ends, this will open a GUI window with the desired graph.

Graph.write(fp=None)

Writes the graph to a file. If no file path is given, a temporary file is used.

Graph3DBars

class music21.graph.primitives.Graph3DBars(*args, **keywords)

Graph multiple parallel bar graphs in 3D.

Data definition: A dictionary where each key forms an array sequence along the z plane (which is depth) For each dictionary, a list of value pairs, where each pair is the (x, y) coordinates.

>>> import random
>>> g = graph.primitives.Graph3DBars()
>>> data = []
>>> ri = random.randint
>>> for i in range(1, 10 + 1):
...    q = [i, i//2, 10 - i]
...    data.append(q)
>>> g.data = data
>>> g.process()

Graph3DBars bases

Graph3DBars read/write properties

Read/write properties inherited from Graph:

Graph3DBars methods

Graph3DBars.process()
Graph3DBars.renderSubplot(subplot)

Methods inherited from Graph:

GraphColorGrid

class music21.graph.primitives.GraphColorGrid(*args, **kwargs)

Grid of discrete colored “blocks” to visualize results of a windowed analysis routine.

Data is provided as a list of lists of colors, where colors are specified as a hex triplet, or the common HTML color codes, and based on analysis-specific mapping of colors to results.

>>> g = graph.primitives.GraphColorGrid()
>>> data = [['#55FF00', '#9b0000', '#009b00'],
...         ['#FFD600', '#FF5600'],
...         ['#201a2b', '#8f73bf', '#a080d5', '#403355', '#999999']]
>>> g.data = data
>>> g.process()
../_images/GraphColorGrid.png

GraphColorGrid bases

GraphColorGrid read/write properties

Read/write properties inherited from Graph:

GraphColorGrid methods

GraphColorGrid.renderSubplot(subplot)

Methods inherited from Graph:

GraphColorGrid instance variables

GraphColorGrid.hideLeftBottomSpines

bool to hide the left and bottom axis spines; default True

GraphColorGridLegend

class music21.graph.primitives.GraphColorGridLegend(*args, **keywords)

Grid of discrete colored “blocks” where each block can be labeled

Data is provided as a list of lists of colors, where colors are specified as a hex triplet, or the common HTML color codes, and based on analysis-specific mapping of colors to results.

>>> g = graph.primitives.GraphColorGridLegend()
>>> data = []
>>> data.append(('Major', [('C#', '#00AA55'), ('D-', '#5600FF'), ('G#', '#2B00FF')]))
>>> data.append(('Minor', [('C#', '#004600'), ('D-', '#00009b'), ('G#', '#00009B')]))
>>> g.data = data
>>> g.process()
../_images/GraphColorGridLegend.png

GraphColorGridLegend bases

GraphColorGridLegend read/write properties

Read/write properties inherited from Graph:

GraphColorGridLegend methods

GraphColorGridLegend.makeOneRowOfGraph(figure, rowIndex, rowLabel, rowData)

Makes a subplot for one row of data (such as for the Major label) and returns a matplotlib.axes.AxesSubplot instance representing the subplot.

Here we create an axis with a part of Scriabin’s mapping of colors to keys in Prometheus: The Poem of Fire.

>>> import matplotlib.pyplot
>>> gcgl = graph.primitives.GraphColorGridLegend()
>>> rowData = [('C', '#ff0000'), ('G', '#ff8800'), ('D', '#ffff00'),
...            ('A', '#00ff00'), ('E', '#4444ff')]
>>> gcgl.data = [['Scriabin Mapping', rowData]]
>>> fig = matplotlib.pyplot.figure()
>>> subplot = gcgl.makeOneRowOfGraph(fig, 0, 'Scriabin Mapping', rowData)
>>> subplot
<matplotlib...AxesSubplot object at 0x111e13828>
GraphColorGridLegend.renderSubplot(subplot)

Methods inherited from Graph:

GraphColorGridLegend instance variables

GraphColorGridLegend.hideLeftBottomSpines

bool to hide the left and bottom axis spines; default True

GraphGroupedVerticalBar

class music21.graph.primitives.GraphGroupedVerticalBar(*args, **keywords)

Graph the count of on or more elements in vertical bars

Data set is simply a list of x and y pairs, where there is only one of each x value, and y value is a list of values

>>> from collections import OrderedDict
>>> g = graph.primitives.GraphGroupedVerticalBar()
>>> lengths = OrderedDict( [('a', 3), ('b', 2), ('c', 1)] )
>>> data = [('bar' + str(x), lengths) for x in range(3)]
>>> data
[('bar0', OrderedDict([('a', 3), ('b', 2), ('c', 1)])),
 ('bar1', OrderedDict([('a', 3), ('b', 2), ('c', 1)])),
 ('bar2', OrderedDict([('a', 3), ('b', 2), ('c', 1)]))]
>>> g.data = data
>>> g.process()

GraphGroupedVerticalBar bases

GraphGroupedVerticalBar read/write properties

Read/write properties inherited from Graph:

GraphGroupedVerticalBar methods

GraphGroupedVerticalBar.labelBars(subplot, rects)
GraphGroupedVerticalBar.renderSubplot(subplot)

Methods inherited from Graph:

GraphHistogram

class music21.graph.primitives.GraphHistogram(*args, **keywords)

Graph the count of a single element.

Data set is simply a list of x and y pairs, where there is only one of each x value, and y value is the count or magnitude of that value

>>> import random
>>> g = graph.primitives.GraphHistogram()
>>> g.graphType
'histogram'
>>> data = [(x, random.choice(range(30))) for x in range(50)]
>>> g.data = data
>>> g.process()
../_images/GraphHistogram.png

GraphHistogram bases

GraphHistogram read/write properties

Read/write properties inherited from Graph:

GraphHistogram methods

GraphHistogram.renderSubplot(subplot)

Methods inherited from Graph:

GraphHistogram instance variables

GraphHistogram.binWidth

Size of each bin; if the bins are equally spaced at intervals of 1, then 0.8 is a good default to allow a little space. 1.0 will give no space.

GraphHorizontalBar

class music21.graph.primitives.GraphHorizontalBar(*args, **keywords)

Numerous horizontal bars in discrete channels, where bars can be incomplete and/or overlap.

Data provided is a list of pairs, where the first value becomes the key, the second value is a list of x-start, x-length values.

>>> a = graph.primitives.GraphHorizontalBar()
>>> data = [('Chopin', [(1810, 1849-1810)]),
...         ('Schumanns', [(1810, 1856-1810), (1819, 1896-1819)]),
...         ('Brahms', [(1833, 1897-1833)])]
>>> a.data = data
>>> a.process()
../_images/GraphHorizontalBar.png

GraphHorizontalBar bases

GraphHorizontalBar read-only properties

GraphHorizontalBar.barHeight

GraphHorizontalBar read/write properties

Read/write properties inherited from Graph:

GraphHorizontalBar methods

GraphHorizontalBar.renderSubplot(subplot)

Methods inherited from Graph:

GraphHorizontalBar instance variables

GraphHorizontalBar.barSpace

Amount of vertical space each bar takes; default 8

GraphHorizontalBar.margin

Space around the bars, default 2

GraphHorizontalBarWeighted

class music21.graph.primitives.GraphHorizontalBarWeighted(*args, **keywords)

Numerous horizontal bars in discrete channels, where bars can be incomplete and/or overlap, and can have different heights and colors within their respective channel.

GraphHorizontalBarWeighted bases

GraphHorizontalBarWeighted read-only properties

GraphHorizontalBarWeighted.barHeight

GraphHorizontalBarWeighted read/write properties

Read/write properties inherited from Graph:

GraphHorizontalBarWeighted methods

GraphHorizontalBarWeighted.renderSubplot(subplot)

Methods inherited from Graph:

GraphHorizontalBarWeighted instance variables

GraphHorizontalBarWeighted.barSpace

Amount of vertical space each bar takes; default 8

GraphHorizontalBarWeighted.margin

Space around the bars, default 2

GraphNetworxGraph

class music21.graph.primitives.GraphNetworxGraph(*args, **keywords)

Grid a networkx graph – which is a graph of nodes and edges. Requires the optional networkx module.

GraphNetworxGraph bases

GraphNetworxGraph read/write properties

Read/write properties inherited from Graph:

GraphNetworxGraph methods

GraphNetworxGraph.renderSubplot(subplot)

Methods inherited from Graph:

GraphNetworxGraph instance variables

GraphNetworxGraph.hideLeftBottomSpines

bool to hide the left and bottom axis spines; default True

GraphNetworxGraph.networkxGraph

An instance of a networkx graph object.

GraphScatter

class music21.graph.primitives.GraphScatter(*args, **keywords)

Graph two parameters in a scatter plot. Data representation is a list of points of values.

>>> g = graph.primitives.GraphScatter()
>>> data = [(x, x * x) for x in range(50)]
>>> g.data = data
>>> g.process()
../_images/GraphScatter.png

GraphScatter bases

GraphScatter read/write properties

Read/write properties inherited from Graph:

GraphScatter methods

GraphScatter.renderSubplot(subplot)

Methods inherited from Graph:

GraphScatterWeighted

class music21.graph.primitives.GraphScatterWeighted(*args, **keywords)

A scatter plot where points are scaled in size to represent the number of values stored within.

>>> g = graph.primitives.GraphScatterWeighted()
>>> data = [(23, 15, 234), (10, 23, 12), (4, 23, 5), (15, 18, 120)]
>>> g.data = data
>>> g.process()
../_images/GraphScatterWeighted.png

GraphScatterWeighted bases

GraphScatterWeighted read-only properties

GraphScatterWeighted.rangeDiameter

GraphScatterWeighted read/write properties

Read/write properties inherited from Graph:

GraphScatterWeighted methods

GraphScatterWeighted.renderSubplot(subplot)

Methods inherited from Graph:

GraphScatterWeighted instance variables

GraphScatterWeighted.maxDiameter

the maximum diameter of any ellipse, default 1.25

GraphScatterWeighted.minDiameter

the minimum diameter of any ellipse, default 0.25