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)

нужно посмотреть зависимости между нашими переменными интереса (loudness danceability speechness acousticness liveness) и всякими разными другими типа - explicit - duration - artist_tier (вот это вероятно особенно важно) - mode

вот то что богдан писал что я безуспешно пыталась сделать это было между explicit и artist tier, но так и не поняла как сделать это на одном графике

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

#Уберем индексы
spotify_numeric <- spotify1[, sapply(spotify1, is.numeric)]
spotify_numeric <- spotify_numeric[, !names( spotify_numeric) %in% c('X')]
#Корреляционная матрица для данных
palette = colorRampPalette(c("purple4", "white", "pink2"))(20)
correlation_matrix <- cor(spotify_numeric)
corrplot(correlation_matrix, method = "color", col = palette, tl.col = "black")
mtext("Correlation Matrix", at=-10, line=-0.5, cex=2)

что-то что показывает неравное распределение треков по популярности артиста. мб диаграмма рассеивания, где уже покрашены точки в зависимости от artist_tier

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

##Графики ксеши

artist_tier_1_number = sum(spotify1$artist_tier == '1')
artist_tier_2_number = sum(spotify1$artist_tier == '2')
artist_tier_3_number = sum(spotify1$artist_tier == '3')
artist_tier_4_number = sum(spotify1$artist_tier == '4')
ggplot(spotify1, aes(x=explicit, y=artist_tier_1_number)) +
geom_bar(stat = "identity")

ggplot(spotify1, aes(x=explicit, y=artist_tier_2_number)) +
  geom_bar(stat = "identity")

ggplot(spotify1, aes(x=explicit, y=artist_tier_3_number)) +
geom_bar(stat = "identity")

ggplot(spotify1, aes(x=explicit, y=artist_tier_4_number)) +
geom_bar(stat = "identity")

#Громкость(loudness)
spotify1 %>%
ggplot(aes(y = popularity, x = loudness, color=period)) +
geom_boxplot() +
labs(y = 'Популярность',
x = 'Громкость, Дб')

#танцевальность (danceability)
spotify1 %>%
ggplot(aes(y = popularity, x = danceability, color=period)) +
geom_boxplot()+
labs(y = 'Популярность',
x = 'танцевальность')

##всякая фигня

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

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

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

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 = ~interaction(artist_tier, mode), type = "box") %>%
  plotly::layout(yaxis = list(title = "зависимость"))
#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()
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
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()