Show the code
import pandas as pd
import numpy as np
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
This code requires that the user supplements their own client_id
and client_secret
which can be obtained after registering to developer account for Spotify API. The code will not run without these. However, the visualisation part of the code works with the save data (data/top_n_track_features2.csv
).
import pandas as pd
import numpy as np
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
= 'YOUR_CLIENT_ID_HERE'
client_id = 'YOUR_SECRET_KEY_HERE'
client_secret
= spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=client_id,
sp =client_secret))
client_secret
= sp.search(q='The Beatles', limit=20)
results for idx, track in enumerate(results['tracks']['items']):
print(idx, track['name'])
= results['tracks']['items'][18] # help is 18
track print(track['name'])
print(track['href'])
print(track['popularity'])
print("===========PREVIEW===========")
print(track['preview_url'])
print("===========PREVIEW===========")
= sp.audio_features(track['id'])
a
print(a[0]['valence']) # Help!: 0.763, Yesterday: 0.315
print(a[0]['energy']) # Help!: 0.725, Yesterday: 0.179
print(a[0]['tempo']) # Help!: 95.003, Yesterday: 96.53
print(a[0]['loudness']) # Help!: -7.576, Yesterday: -11.83
print(a[0]['acousticness']) # Help!: 0.188, Yesterday: 0.879
print("===========GENRE===========")
= []
name = []
Tid = []
valence = []
energy = []
tempo = []
loudness = []
instrumentalness = []
acousticness = []
danceability
# get 500 tracks, 50 each time
= np.arange(1, 500, 10)
offset_vals
for i in range(50):
= sp.search(q='genre:pop & year:1964-1966', limit=10,
results =offset_vals[i])
offsetfor idx, track in enumerate(results['tracks']['items']):
'name'])
name.append(track['id'])
Tid.append(track[= sp.audio_features(track['id'])
a 0]['valence'])
valence.append(a[0]['energy'])
energy.append(a[0]['instrumentalness'])
instrumentalness.append(a[0]['acousticness'])
acousticness.append(a[0]['danceability'])
danceability.append(a[0]['tempo'])
tempo.append(a[0]['loudness'])
loudness.append(a[print(i, ':', idx)
# Store in data frame and save to a file
= pd.DataFrame({'valence': valence, 'energy': energy, 'tempo': tempo,
df 'acousticness': acousticness,
'loudness': loudness, 'id': Tid})
'data/top_n_track_features2.csv') df.to_csv(
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
# Get data (from a previous process)
= pd.read_csv('data/top_n_track_features2.csv')
d
# set graphic (seaborn) theme
sns.set_theme()"whitegrid")
sns.set_style(
= plt.figure()
fig 8)
fig.set_figheight(9)
fig.set_figwidth(
# Define multiple plots
= plt.subplot2grid(shape=(2, 2), loc=(0, 0))
ax1 = plt.subplot2grid(shape=(2, 2), loc=(0, 1))
ax2 = plt.subplot2grid(shape=(2, 2), loc=(1, 0))
ax3 = plt.subplot2grid(shape=(2, 2), loc=(1, 1))
ax4
='valence', data=d, color='blue', ax=ax1)
sns.histplot(x'Valence (0-1)')
ax1.set_xlabel(0.763, color='red', linewidth=2, alpha=.7)
ax1.axes.axvline(0.763, ax1.get_ylim()[1], "Help!", size=12, backgroundcolor='0.9',
ax1.text(="center", va="top", alpha=0.85)
ha0.315, color='green', linewidth=2, alpha=.7)
ax1.axes.axvline(0.315, ax1.get_ylim()[1], "Yesterday", size=12, backgroundcolor='0.9',
ax1.text(="center", va="top", alpha=0.85)
ha0, 1])
ax1.set_xlim([0, 1.1, 0.20))
ax1.set_xticks(np.arange(
='energy', data=d, color='blue', ax=ax2)
sns.histplot(x'Energy (0-1)')
ax2.set_xlabel(0.725, color='red', linewidth=2, alpha=.7)
ax2.axes.axvline(0.725, ax2.get_ylim()[1], "Help!", size=12, backgroundcolor='0.9',
ax2.text(="center", va="top", alpha=0.85)
ha0.179, color='green', linewidth=2, alpha=.7)
ax2.axes.axvline(0.179, ax2.get_ylim()[1], "Yesterday", size=12, backgroundcolor='0.9',
ax2.text(="center", va="top", alpha=0.85)
ha0, 1])
ax2.set_xlim([0, 1.1, 0.20))
ax2.set_xticks(np.arange(
='tempo', data=d, color='blue', ax=ax3)
sns.histplot(x'Tempo (BPM)')
ax3.set_xlabel(95, color='red', linewidth=2, alpha=.7)
ax3.axes.axvline(90, ax3.get_ylim()[1], "Help!", size=12, backgroundcolor='0.9',
ax3.text(="right", va="top", alpha=0.85)
ha96.5, color='green', linewidth=2, alpha=.7)
ax3.axes.axvline(100, ax3.get_ylim()[1], "Yesterday", size=12, backgroundcolor='0.9',
ax3.text(="left", va="top", alpha=0.85)
ha
='acousticness', data=d, color='blue', ax=ax4)
sns.histplot(x'Acousticness (0-1)')
ax4.set_xlabel(0.188, color='red', linewidth=2, alpha=.7)
ax4.axes.axvline(0.188, ax4.get_ylim()[1], "Help!", size=12, backgroundcolor='0.9',
ax4.text(="center", va="top", alpha=0.85)
ha0.879, color='green', linewidth=2, alpha=.7)
ax4.axes.axvline(0.879, ax4.get_ylim()[1], "Yesterday", size=12, backgroundcolor='0.9',
ax4.text(="center", va="top", alpha=0.85)
ha0, 1])
ax4.set_xlim([0, 1.1, 0.20))
ax4.set_xticks(np.arange(
fig.tight_layout() plt.show()