Create Radar Chart to analyze Playlist
Tags: #spotify #python #spotipy #analytics

Input

Import libraries

First you need to set up Spotify API at https://developer.spotify.com to get clientID and clientSecret
1
!pip install spotify
2
!pip install spotipy
Copied!
1
import json
2
import spotipy
3
import pandas as pd
4
from spotipy.oauth2 import SpotifyClientCredentials
5
from sklearn.preprocessing import MinMaxScaler
6
import matplotlib.pyplot as plt
7
from math import pi
Copied!

Variables

1
#Retrieve Client credentials from Spotify Developer Page
2
client_id = ''
3
client_secret = ''
4
5
client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)
6
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
7
8
#Retrieve playlist_id by getting the Spotify URI of any playlist
9
playlist_id = "spotify:playlist:5fqIcaihygJQGberg0wy0G"
10
results = sp.playlist(playlist_id)
11
12
min_max_scaler = MinMaxScaler()
Copied!

Model

Function

1
#Function to Convert JSON to Dataframe
2
# create a list of song ids
3
ids=[]
4
5
for item in results['tracks']['items']:
6
track = item['track']['id']
7
ids.append(track)
8
9
song_meta={'id':[],'album':[], 'name':[],
10
'artist':[],'explicit':[],'popularity':[]}
11
12
for song_id in ids:
13
# get song's meta data
14
meta = sp.track(song_id)
15
16
# song id
17
song_meta['id'].append(song_id)
18
19
# album name
20
album=meta['album']['name']
21
song_meta['album']+=[album]
22
23
# song name
24
song=meta['name']
25
song_meta['name']+=[song]
26
27
# artists name
28
s = ', '
29
artist=s.join([singer_name['name'] for singer_name in meta['artists']])
30
song_meta['artist']+=[artist]
31
32
# explicit: lyrics could be considered offensive or unsuitable for children
33
explicit=meta['explicit']
34
song_meta['explicit'].append(explicit)
35
36
# song popularity
37
popularity=meta['popularity']
38
song_meta['popularity'].append(popularity)
39
40
song_meta_df=pd.DataFrame.from_dict(song_meta)
41
42
# check the song feature
43
features = sp.audio_features(song_meta['id'])
44
# change dictionary to dataframe
45
features_df=pd.DataFrame.from_dict(features)
46
47
# convert milliseconds to mins
48
# duration_ms: The duration of the track in milliseconds.
49
# 1 minute = 60 seconds = 60 × 1000 milliseconds = 60,000 ms
50
features_df['duration_ms']=features_df['duration_ms']/60000
51
52
# combine two dataframe
53
final_df=song_meta_df.merge(features_df)
Copied!
1
#Function for Data Pre-Processing
2
music_features=features_df[['danceability','energy','loudness','speechiness',
3
'acousticness','instrumentalness','liveness','valence',
4
'tempo','duration_ms']]
5
6
music_features.describe()
7
#Transforming Data so that all values are in the range 0 to 1
8
#To turn of warning run below command
9
pd.set_option('mode.chained_assignment', None)
10
music_features.loc[:]=min_max_scaler.fit_transform(music_features.loc[:])
Copied!

Output

Display result

1
#Radar Chart with several heads from DataFrame
2
#Creating Radar Chart
3
fig = plt.figure(figsize=(10,10))
4
5
categories=list(music_features.columns)
6
7
N=len(categories)
8
9
value = list(music_features.mean())
10
11
value+=value[:1]
12
angles = [n/float(N)*2*pi for n in range(N)]
13
angles+= angles[:1]
14
15
16
plt.polar(angles,value,color='red')
17
plt.fill(angles,value,alpha=0.7,color='purple')
18
19
plt.title('Playlist Audio Features', size=20, y=1.05)
20
21
plt.xticks(angles[:-1],categories,size=15, color='purple')
22
plt.yticks(color='black', size=15)
23
plt.show()
Copied!
1
Copied!
Last modified 2mo ago
Copy link
Edit on GitHub