Music_data<-read.csv("C:/Users/woody/Desktop/NU/archive_spotify/spotify-2023.csv")
library(caret)
## Warning: 套件 'caret' 是用 R 版本 4.3.2 來建造的
## 載入需要的套件:ggplot2
## Warning: 套件 'ggplot2' 是用 R 版本 4.3.2 來建造的
## 載入需要的套件:lattice
features <- c('danceability_.', 'energy_.', 'valence_.', 'acousticness_.')
preProValues<-preProcess(Music_data[,features], method=c("center","scale"))
normalizeData <- predict(preProValues,Music_data)
set.seed(123)
k<-4
kmResult <- kmeans(normalizeData[, features], centers=k, nstart =20 )
Music_data$cluster <- as.factor(kmResult$cluster)
library(GGally)
## Warning: 套件 'GGally' 是用 R 版本 4.3.2 來建造的
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
# 選擇需要展示的特徵和簇標籤
selected_features <- Music_data[, c('danceability_.', 'energy_.', 'valence_.', 'acousticness_.', 'cluster')]
# 繪製成對關係圖,展示不同簇的分布
ggpairs(selected_features, mapping = aes(color = cluster))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

library(ggplot2)
# 執行PCA分析
pca_result <- prcomp(Music_data[, c('danceability_.', 'energy_.', 'valence_.', 'acousticness_.')], scale = TRUE)
# 將PCA結果轉換為數據框,準備作圖
pca_data <- as.data.frame(pca_result$x)
pca_data$cluster <- Music_data$cluster
# 繪製PCA結果的前兩個主成分
ggplot(pca_data, aes(x = PC1, y = PC2, color = cluster)) +
geom_point(alpha = 0.5) +
labs(title = "PCA of Music Data by Cluster", x = "Principal Component 1", y = "Principal Component 2")

library(pheatmap)
## Warning: 套件 'pheatmap' 是用 R 版本 4.3.2 來建造的
library(RColorBrewer)
## Warning: 套件 'RColorBrewer' 是用 R 版本 4.3.1 來建造的
library(tidyr)
library(ggplot2)
library(dplyr)
##
## 載入套件:'dplyr'
## 下列物件被遮斷自 'package:stats':
##
## filter, lag
## 下列物件被遮斷自 'package:base':
##
## intersect, setdiff, setequal, union
# 計算每個簇的特徵平均值
cluster_means <- aggregate(. ~ cluster, data = Music_data[, c('danceability_.', 'energy_.', 'valence_.', 'acousticness_.', 'cluster')], mean)
cluster_means_no_cluster <- cluster_means[, -which(names(cluster_means) == "cluster")]
max_values <- apply(cluster_means_no_cluster, 2, max)
normalized_cluster_means <- sweep(cluster_means_no_cluster, 2, max_values, FUN="/")
normalized_names <- paste0(names(cluster_means_no_cluster), "_normalized")
cluster_means[normalized_names] <- normalized_cluster_means
print(cluster_means)
## cluster danceability_. energy_. valence_. acousticness_.
## 1 1 79.61836 57.28502 45.50725 23.57005
## 2 2 53.72222 41.54321 37.14198 70.59259
## 3 3 55.67717 70.00000 35.61024 12.46850
## 4 4 74.23030 75.42424 74.33939 19.10303
## danceability_._normalized energy_._normalized valence_._normalized
## 1 1.0000000 0.7595041 0.6121552
## 2 0.6747467 0.5507939 0.4996271
## 3 0.6993006 0.9280836 0.4790224
## 4 0.9323265 1.0000000 1.0000000
## acousticness_._normalized
## 1 0.3338884
## 2 1.0000000
## 3 0.1766262
## 4 0.2706096
long_cluster_means <- pivot_longer(cluster_means,
cols = -cluster,
names_to = "Feature",
values_to = "Value")
long_cluster_means_normalized <- pivot_longer(cluster_means,
cols = ends_with("_normalized"),
names_to = "Feature",
values_to = "Value") %>%
mutate(Feature = gsub("_normalized$", "", Feature)) # 移除特徵名中的 '_normalized'
ggplot(long_cluster_means_normalized, aes(x = cluster, y = Value, fill = Feature)) +
geom_bar(stat = "identity", position = position_dodge()) +
theme_minimal() +
labs(title = "Normalized Feature Values by Cluster", x = "Cluster", y = "Normalized Value") +
scale_fill_brewer(palette = "Set3") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))

# 移除簇標籤列
#cluster_means$cluster <- NULL
# 繪製熱圖
#pheatmap(t(cluster_means), main = "Feature Means by Cluster", color = colorRampPalette(rev(brewer.pal(n = 7, name = "RdYlBu")))(100))
#cor(Music_data$acousticness_., Music_data$valence_, use = "complete.obs")
# trans release date to season
Music_data$season <- ifelse(Music_data$released_month %in% c(3, 4, 5), 'Spring',
ifelse(Music_data$released_month %in% c(6, 7, 8), 'Summer',
ifelse(Music_data$released_month %in% c(9, 10, 11), 'Fall', 'Winter')))
# 使用交叉表分析聚類(曲風)與季節的關聯性
table(Music_data$cluster, Music_data$season)
##
## Fall Spring Summer Winter
## 1 46 71 46 44
## 2 43 46 25 48
## 3 58 75 50 71
## 4 62 88 73 107
Music_data$season <- factor(Music_data$season, levels = c("Spring", "Summer", "Fall", "Winter"))
# 可視化
library(ggplot2)
ggplot(Music_data, aes(x = season, fill = cluster)) + geom_bar(position = "dodge") +
labs(title = "Distribution of Clusters (Genres) by Season", x = "Season", y = "Count")
