# Importing necessary packages
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
import warnings
import matplotlib.patches as mpatches
import seaborn as sns
warnings.filterwarnings("ignore")
# Load the dataset
file_path = "Spotify.csv"
# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)
# Display the first few rows of the DataFrame to inspect the data
df.head()
| title | rank | date | artist | url | region | chart | trend | streams | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | Chantaje feat. Maluma | 1 | 2017-01-01 | Shakira | [https://open.spotify.com/track/6mICuAdrwEjh6Y6\\](https://open.spotify.com/track/6mICuAdrwEjh6Y6\… | Argentina | top200 | SAME_POSITION | 253019.0 |
| 1 | Vente Pa Ca feat. Maluma | 2 | 2017-01-01 | Ricky Martin | [https://open.spotify.com/track/7DM4BPaS7uofFul\\](https://open.spotify.com/track/7DM4BPaS7uofFul\… | Argentina | top200 | MOVE_UP | 223988.0 |
| 2 | Reggaetón Lento Bailemos | 3 | 2017-01-01 | CNCO | [https://open.spotify.com/track/3AEZUABDXNtecAO\\](https://open.spotify.com/track/3AEZUABDXNtecAO\… | Argentina | top200 | MOVE_DOWN | 210943.0 |
| 3 | Safari | 4 | 2017-01-01 | J Balvin, Pharrell Williams, BIA, Sky | [https://open.spotify.com/track/6rQSrBHf7HlZjtc\\](https://open.spotify.com/track/6rQSrBHf7HlZjtc\… | Argentina | top200 | SAME_POSITION | 173865.0 |
| 4 | Shaky Shaky | 5 | 2017-01-01 | Daddy Yankee | [https://open.spotify.com/track/58IL315gMSTD37D\\](https://open.spotify.com/track/58IL315gMSTD37D\… | Argentina | top200 | MOVE_UP | 153956.0 |
The first visualization shows the trends of top music in 2017 specifically in Denmark. The trends consist of the song either moving up, moving down,staying the same, or a completely new entry. I chose to use a pie chart to illustrate the trends as it only consists of 4 options and it can be easily visualized in a pie chart.
#Pie Chart
# Filter rows where REGION is Denmark
denmark_df = df[df['region'] == 'Denmark']
# Group by TREND and count occurrences
trend_counts = denmark_df['trend'].value_counts()
# Plotting the pie chart
plt.figure(figsize=(8, 8))
plt.pie(trend_counts, labels=trend_counts.index, autopct='%1.1f%%', startangle=160)
plt.title('Trends in Denmark')
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
The second visualization shows the streams in 2017 in Denmark for the top 25 songs. I chose a bar chart to illustrate this as the streams are larger numbers and would be best visualized in a bar chart as it would best show which songs actually had the most streams versus trying to analyze the large numbers and determine which song had the most streams.
#Bar Chart
# Sorting data
start_row = 2011
end_row = 2210
denmark_2017 = df.iloc[start_row:end_row].copy()
denmark_2017_top25 = denmark_2017.head(25)
# Plotting the bar chart
plt.figure(figsize=(10, 6))
plt.bar(denmark_2017_top25['artist'],denmark_2017_top25['streams'],color='lightpink')
plt.title('Count of Denmark 2017 Top 25 Song Streams')
plt.xlabel('artist')
plt.ylabel('streams')
plt.xticks(rotation=45, ha='right')
plt.show()
The third visualization shows top Spotify songs by stream in 5 regions. I chose a histogram to illustrate this date as each region was able to be a different color in the histogram. The histogram consisted of streams and the frequency of the streams.
#Histogram
histogramdf = df[['region','streams', 'date']]
include_regions = ['Australia', 'Austria', 'Belgium', 'Denmark', 'Columbia', 'Bolivia']
histogramdf = histogramdf[histogramdf['region'].isin(include_regions)]
histogramdf['date']= pd.to_datetime(histogramdf['date'])
histogramdf=histogramdf[histogramdf['date'].dt.year==2017]
histogramdf.drop(columns=['date'], inplace=True)
histogramdf.dropna(inplace=True)
histogramgroup = {region: histogramdf.loc[histogramdf['region']== region, 'streams']
for region in histogramdf['region'].unique()}
for region, streams in histogramgroup.items():
plt.hist(streams, bins=5, alpha = 0.5, label=region)
plt.legend()
plt.xlabel('Streams')
plt.ylabel('Frequency')
plt.title('Histogram of Top Spotify Songs by Stream in 5 Regions')
plt.show()
The fourth visualization shows the total streams and trends in 3 different regions. I chose Denmark, Argentina, and Australia as they are all countries from three different areas in the world. This allows us to really collect data that best represents the global population. Illustrating both the streams and trends at the same time help us better understand the Spotify top song chart and these songs influences on society.
#Nested Pie Chart
#Create Pie Chart df
piechartdf=df[['region', 'streams', 'trend', 'date']]
#Selected 3 Regions to look at in 2017
pie_chart_includes=['Denmark', 'Australia', 'Argentina']
piechartdf= piechartdf[piechartdf['region'].isin(pie_chart_includes)]
piechartdf['date']=pd.to_datetime(piechartdf['date'])
piechartdf=piechartdf[piechartdf['date'].dt.year==2017]
piechartdf.drop(columns=['date'], inplace=True)
piechartdf.dropna(inplace=True)
piechartdf[['streams']]=piechartdf[['streams']].astype(int)
#Get Total Number of Streams
totalStreams=piechartdf['streams'].sum()
outside_colors= ['pink', '#023E8A', 'yellow']
inside_colors= ['#FF69B4', '#FFB6C1', '#F3CFC6', '#fff0f3',
'#0077B6', '#0096C7', '#48CAE4', '#D6EBF2',
'#FDDA0D', '#FFFF8F', '#FFF8DC', '#FFFEE9']
#Create the Pie Chart
fig=plt.figure(figsize=(14,14))
ax=fig.add_subplot(1,1,1)
#Outside Donut
piechartdf.groupby(['region'])['streams'].sum().plot(kind='pie', radius=1.15, pctdistance=0.87, labeldistance=1.1,
wedgeprops=dict(edgecolor='white'),autopct= lambda p:
'{:.2f}%\n({:.0f})'.format(p,(p/100)*piechartdf['streams'].sum()),
textprops={'fontsize':10},
startangle=90,colors=outside_colors)
piedfinnerlabels = ['MOVE_DOWN','MOVE_UP','NEW_ENTRY','SAME_POSITION',
'MOVE_DOWN','MOVE_UP','NEW_ENTRY','SAME_POSITION',
'MOVE_DOWN','MOVE_UP','NEW_ENTRY','SAME_POSITION']
#Inner Donut
piechartdf.groupby(['region','trend'])['streams'].sum().plot(kind = 'pie', radius=0.89, colors=inside_colors,
pctdistance=0.77,labeldistance=0.85,
wedgeprops=dict(edgecolor='white'),
textprops={'fontsize':8},
labels=piedfinnerlabels,
autopct=lambda p:'{:.2f}%\n({:.0f})'.format(p,(p/100)*piechartdf['streams'].sum()),
startangle=90)
#Create the White Circle Center
hole = plt.Circle((0,0), 0.35, fc='white')
fig1 = plt.gcf()
fig1.gca().add_artist(hole)
#Create Titles
ax.yaxis.set_visible(False)
plt.title('Total Streams & Trends by region in 2017', fontsize=18)
ax.text(0,0, 'Total Streams 2017', size=10, ha='center', va='center')
ax.axis('equal')
plt.tight_layout()
plt.show()
The fifth visualization illustrates the top artist in 2017 in Denmark. I specifically chose 6 artists at random and illustrated how many streams each artist recieive compared to the other. I did this in a scatter plot to most easily illustrate the significance each artist has in Denmark specifically.
#Scatter Plot
# Create Scatter Plot df
scatterdf= ['artist', 'streams', 'date']
scatterdf=pd.DataFrame({'artist':['Clean Bandit', 'Gilli', 'Starley', 'Gulddreng', 'James Arthur', 'NODE'], 'streams':[30000,40000,50000,60000,70000,80000]})
#Define size of Scatter Plot
plt.figure(figsize=(10,6))
#Create Scatter Plot
plt.scatter(scatterdf['artist'],scatterdf['streams'])
plt.title('Scatter Plot: Top 6 Artist in the year 2017')
plt.xlabel('artist')
plt.ylabel('streams')
plt.xticks(rotation=90)
plt.grid(True)
plt.show()