Published
Edited
May 25, 2020
Importers
3 stars
Insert cell
Insert cell
chart = {
const data = streams
//exclude skipped songs. undercounts hours, but improves track counts
.filter(x=> x.msPlayed >= 1000*30)
//convert miliseconds to hours
.map(x=> ({...x, hrsPlayed: x.msPlayed/(60*60*1000) }))
// add x-range filter for top chart.
const brush = vl.selectInterval().encodings('x');
// sum of listening time by date
const top = vl.markBar()
.data(data)
.encode(vl.x().fieldT('endTime').timeUnit('yearmonthdate'),
vl.y().sum('hrsPlayed'))
.select(brush)
.width(width * .83) // no significane to this number, just something that mostly worked
.height(125)
.title("Hours Streaming by Day (click and drag to filter top lists by date)")
const bar = (str) => {
const marks =
vl.markBar()
.data(data)
.transform(
vl.filter(brush),
vl.aggregate(vl.count().as('streams')).groupby(str, 'artistName'),
// using row_number instead of rank
vl.window(vl.row_number().as('Rank')).sort(vl.field('streams').order('descending')),
vl.filter('datum["Rank"]<=15')
)
.encode(vl.y().fieldN(str).sort('-x'),
vl.x().fieldQ('streams'),
vl.text().fieldN('streams'))
.title(str)
.width(width/3) // another number that mostly worked
return vl.layer(marks, marks.markText({align : "right", color: "white", dx: -5}))
}
const artists = bar('artistName').title("Top Artists")
const songs = bar('trackName').title("Top Songs")
return vl.vconcat(top, vl.hconcat(artists, songs))
.render()
}
Insert cell
streams = [
// If you requested your own data from spotify, you should be able upload it as an Observable attachment, replacing what I attached.
// If your streaming history contains more or fewer files than mine, you'll need to adjust this block of code.
await FileAttachment("StreamingHistory0.json").json(),
await FileAttachment("StreamingHistory1.json").json(),
await FileAttachment("StreamingHistory2.json").json(),
//await FileAttachment("StreamingHistory3.json").json(),

].flat()
Insert cell
import {vl} from '@vega/vega-lite-api'
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more