Skip to content

Instantly share code, notes, and snippets.

@dharasim
Last active February 19, 2019 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharasim/c7c71b0af482f11090a35782eea853c3 to your computer and use it in GitHub Desktop.
Save dharasim/c7c71b0af482f11090a35782eea853c3 to your computer and use it in GitHub Desktop.
Pitch Class Barplot
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vega Lite Barplot</title>
<!-- Import Vega 4 & Vega-Lite 3 (does not have to be from CDN) -->
<script src="https://cdn.jsdelivr.net/npm/vega@4"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@3.0.0-rc12"></script>
<!-- Import vega-embed -->
<script src="https://cdn.jsdelivr.net/npm/vega-embed@3"></script>
</head>
<body>
<input type="text" oninput="update(this.value)" placeholder="0 0 0 4 7 7">
<br>
<div id="vis"></div>
<script language="javascript" src="scripts.js"></script>
<script>renderPitchClassCounts('#vis', [0, 0, 0, 4, 7, 7]);</script>
</body>
</html>
// range of integers [0,1,2,...,n-1]
function range(n) {
return [...Array(n).keys()];
}
function countPitchClasses(pitches) {
return pitches.reduce(
function(counter, pitch) {
counter[pitch % 12] += 1;
return counter;
},
range(12).reduce(
function(pcs, pc) {
pcs[pc] = 0;
return pcs
},
{}
)
)
}
function update(input) {
var pitches = input.split(" ").map(s => parseInt(s));
renderPitchClassCounts('#vis', pitches);
}
function renderPitchClassCounts(outputID, pitches) {
var pitchClassCounts = countPitchClasses(pitches);
var vegaLiteValues = range(12).map(
function(pc) {
return {"pitch class": pc, "count": pitchClassCounts[pc]}
}
);
var pitchClassPlot = {
"description": "Pitch Class Counts",
"width": 360,
"mark": "bar",
"data": {"values": vegaLiteValues},
"encoding": {
"x": {"field": "pitch class", "type": "ordinal"},
"y": {"field": "count", "type": "quantitative"},
"tooltip": {"field": "count", "type": "quantitative"}
}
};
pitchClassPlot["data"] = {"values": vegaLiteValues};
vegaEmbed(outputID, pitchClassPlot).catch(console.warn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment