library(readr)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(conflicted)
library(corrplot)
## corrplot 0.92 loaded
library(plotly)
## Loading required package: ggplot2
library(ggplot2)

spotify <- read.csv('music_data.csv', sep=',')

tier4 <- summary(spotify$principal_artist_followers)['Min.'] : summary(spotify$principal_artist_followers)['1st Qu.']
tier3 <- (summary(spotify$principal_artist_followers)['1st Qu.'] + 1) : summary(spotify$principal_artist_followers)['Median']
tier2 <- (summary(spotify$principal_artist_followers)['Median'] + 1) : summary(spotify$principal_artist_followers)['3rd Qu.']
tier1 <- (summary(spotify$principal_artist_followers)['3rd Qu.'] + 1) : summary(spotify$principal_artist_followers)['Max.']

spotify1 <- spotify %>%
mutate(artist_tier = case_when(principal_artist_followers %in% tier1 ~ 1,
principal_artist_followers %in% tier2 ~ 2,
principal_artist_followers %in% tier3 ~ 3,
principal_artist_followers %in% tier4 ~ 4
))

#Добавим переменную по временным периодам
spotify1 <- spotify1 %>%
mutate(period = case_when(year >= 1996 & year <= 2000 ~ '1',
year >= 2001 & year <= 2005 ~ '2',
year >= 2006 & year <= 2010 ~ '3',
year >= 2011 & year <= 2015 ~ '4',
year >= 2016 & year <= 2020 ~ '5'
))

spotify1 <- spotify1 %>%
dplyr::filter(!is.na(period))
head(spotify1)
##   X                       track_name                      available_markets
## 1 0 "The Take Over, The Breaks Over" Europe, Africa, Asia, America, Oceania
## 2 1                               #1 Europe, Africa, Asia, America, Oceania
## 3 3                              #41                                America
## 4 4               $outh $ide $uicide Europe, Africa, Asia, America, Oceania
## 5 5                                & Europe, Africa, Asia, America, Oceania
## 6 8   (Can't Get My) Head Around You Europe, Africa, Asia, America, Oceania
##   duration_ms explicit      artists_names principal_artist_name
## 1      213586    False       Fall Out Boy          Fall Out Boy
## 2      198760     True              Nelly                 Nelly
## 3      399800    False Dave Matthews Band    Dave Matthews Band
## 4      169319     True  $uicideboy$;Pouya           $uicideboy$
## 5      194586    False         Tally Hall            Tally Hall
## 6      134760    False      The Offspring         The Offspring
##   principal_artist_followers acousticness danceability energy key liveness
## 1                   10246090      0.00614        0.609  0.917   9   0.0775
## 2                    2500796      0.02360        0.690  0.592   7   0.5600
## 3                    1923688      0.00199        0.577  0.726   4   0.1580
## 4                    5947594      0.00538        0.797  0.516   1   0.0728
## 5                     591548      0.00135        0.532  0.880  11   0.3480
## 6                    5170330      0.00807        0.539  0.814   7   0.0916
##   loudness mode speechiness   tempo time_signature valence popularity year
## 1   -2.563    B      0.0477 149.948              4  0.6700         63 2007
## 2   -5.973    B      0.3000 179.980              4  0.4660         57 2002
## 3   -8.011    A      0.0299 107.416              4  0.7640         57 1996
## 4   -6.286    B      0.0832 109.993              4  0.0478         72 2015
## 5   -5.119    B      0.0362  95.921              4  0.7270         63 2011
## 6   -4.643    B      0.0771 143.280              4  0.6460         70 2003
##    sound_system artist_tier period
## 1       D Major           1      3
## 2       C Major           3      2
## 3       C Minor           3      1
## 4 F-Sharp Major           2      4
## 5       E Major           4      4
## 6       C Major           2      2
spotify1$period <- as.factor(spotify1$period)

spotify1$key <- as.factor(spotify1$key)
spotify1$artist_tier <- as.factor(spotify1$artist_tier)
spotify1 <- subset(spotify1, tempo!=0)

#Матрица кореляции

# Выбор нужных переменных из датасета spotify1
spotify1$mode <- as.factor(spotify1$mode)
spotify1$mode <- as.numeric(spotify1$mode)
selected_variables <- spotify1[, c("duration_ms", "principal_artist_followers", "acousticness", 
                                   "danceability", "liveness", "loudness", "speechiness",
                                   "tempo", "valence", "popularity", "mode")]

# Создание корреляционной матрицы
correlation_matrix <- cor(selected_variables)

# Настройка палитры цветов
palette <- colorRampPalette(c("purple4", "white", "pink2"))(20)

# Построение корреляционной матрицы с использованием corrplot
corrplot(correlation_matrix, method = "color", col = palette, tl.col = "black")
mtext("Correlation Matrix", at=-10, line=-0.5, cex=2)

library(ggplot2)
library(gridExtra)

# Громкость (loudness)
plot1 <- ggplot(data = spotify1, aes(x = loudness, y = popularity, color = period)) +
  geom_boxplot() +
  labs(title = "Box-Plot for Loudness", y = 'popularity', x = 'loudness')

# Танцевальность (danceability)
plot2 <- ggplot(data = spotify1, aes(x = danceability, y = popularity, color = period)) +
  geom_boxplot() +
  labs(title = "Box-Plot for Danceability", y = 'popularity', x = 'danceability')

# Количество текста (speechiness)
plot3 <- ggplot(data = spotify1, aes(x = speechiness, y = popularity, color = period)) +
  geom_boxplot() +
  labs(title = "Box-Plot for Speechiness", y = 'popularity', x = 'speechiness')

# Акустичность (acousticness)
plot4 <- ggplot(data = spotify1, aes(x = acousticness, y = popularity, color = period)) +
  geom_boxplot() +
  labs(title = "Box-Plot for Acousticness", y = 'popularity', x = 'acousticness')

# Живость исполнения (liveness)
plot5 <- ggplot(data = spotify1, aes(x = liveness, y = popularity, color = artist_tier)) +
  geom_boxplot() +
  labs(title = "Box-Plot for Liveness", y = 'popularity', x = 'liveness')

# Комбинированный график
combined_plot <- grid.arrange(plot1, plot2, plot3, plot4, plot5, ncol = 2, top = "Box-Plots for Regressors")

# Вывод графика
print(combined_plot)
## TableGrob (4 x 2) "arrange": 6 grobs
##   z     cells    name                grob
## 1 1 (2-2,1-1) arrange      gtable[layout]
## 2 2 (2-2,2-2) arrange      gtable[layout]
## 3 3 (3-3,1-1) arrange      gtable[layout]
## 4 4 (3-3,2-2) arrange      gtable[layout]
## 5 5 (4-4,1-1) arrange      gtable[layout]
## 6 6 (1-1,1-2) arrange text[GRID.text.731]

неравное распределение треков по популярности артиста

plot_ly(spotify1, x = ~principal_artist_followers, y =  ~popularity, color=~artist_tier)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
plot_ly(spotify1, x = ~popularity, color = ~artist_tier, colors = "PuRd")
## No trace type specified:
##   Based on info supplied, a 'histogram' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#histogram
one_plot <- function(d) {
  plot_ly(d, x = ~popularity) %>%
    add_annotations(
      ~unique(artist_tier), x = 0.5, y = 1, 
      xref = "paper", yref = "paper", showarrow = FALSE
    )
}

spotify1 %>%
  split(.$artist_tier) %>%
  lapply(one_plot) %>% 
  subplot(nrows = 2, shareX = TRUE, titleX = FALSE) %>%
  hide_legend()
## No trace type specified:
##   Based on info supplied, a 'histogram' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#histogram
## No trace type specified:
##   Based on info supplied, a 'histogram' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#histogram
## No trace type specified:
##   Based on info supplied, a 'histogram' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#histogram
## No trace type specified:
##   Based on info supplied, a 'histogram' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#histogram

##Cмотрим на переменные интереса и контрольную key

p <- plot_ly(spotify1, y = ~loudness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~key)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~danceability, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~key)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~speechiness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~key)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~acousticness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~key)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~liveness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~key)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()

##Cмотрим на переменные интереса и контрольную mode

p <- plot_ly(spotify1, y = ~loudness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~ mode)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~danceability, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~mode)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~speechiness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~mode)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~acousticness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~mode)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~liveness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~mode)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()

##Cмотрим на переменные интереса и контрольную explicit

p <- plot_ly(spotify1, y = ~loudness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~ explicit)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~danceability, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~explicit)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~speechiness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~explicit)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~acousticness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~explicit)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~liveness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~explicit)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()

##Cмотрим не переменные интереса и контрольную artist_tier

p <- plot_ly(spotify1, y = ~loudness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~ artist_tier)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~danceability, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~artist_tier)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~speechiness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~artist_tier)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~acousticness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~artist_tier)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()
p <- plot_ly(spotify1, y = ~liveness, color = I("black"), 
             alpha = 0.1, boxpoints = "suspectedoutliers")
p1 <- p %>% add_boxplot(x = "Overall")
p2 <- p %>% add_boxplot(x = ~artist_tier)
subplot(
  p1, p2, shareY = TRUE,
  widths = c(0.2, 0.8), margin = 0
) %>% hide_legend()

##Cмотрим на переменные интереса и контрольную duration_ms

plot_ly(spotify1, x = ~loudness, y = ~duration_ms)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
plot_ly(spotify1, x = ~danceability, y = ~duration_ms)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
plot_ly(spotify1, x = ~speechiness, y = ~duration_ms)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
plot_ly(spotify1, x = ~acousticness, y = ~duration_ms)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
plot_ly(spotify1, x = ~liveness, y = ~duration_ms)
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode

#Распределение громкости в зависимости от тональности

plot_ly(spotify1, x = ~loudness, color = ~mode, colors = "Accent")
## No trace type specified:
##   Based on info supplied, a 'histogram' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#histogram
## Warning: textfont.color doesn't (yet) support data arrays
## Warning in min(x, na.rm = na.rm): no non-missing arguments to min; returning
## Inf
## Warning in max(x, na.rm = na.rm): no non-missing arguments to max; returning
## -Inf
## Warning: textfont.color doesn't (yet) support data arrays

#Распределение громкости в зависимости от популярности артиста и тональности, в которой написана песня

plot_ly(spotify1, x = ~loudness, y = ~interaction(artist_tier, mode), color = ~explicit, type = "box") %>%
 plotly:: layout(yaxis = list(title = "зависимость"))
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels

## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
plot_ly(spotify1, x = ~loudness, y = ~key, type = "scatter", mode = "markers", color = ~explicit)
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels

## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels