## This is part 2 to streams per source
## It takes the details table and expands.

lib(ggplot2)


.myf(dictspot)
DT.streams_per_source_with_detail

## AGGREGATE BY MONTH
DT <- DT.streams_per_source_with_detail
group <- c("user_country", "account_type")
group <- c("user_country")
group <- c("account_type")
group <- NULL

byCols <- c("source", group)
monthGroup <- c("month", group)

DT.monthly_streams_per_source <- aggregateMonthly(DT, dateCol="download_date", newCol.nm="month", byCols=c("days_of_data_per_month", byCols), colsToAgg="streams")

## Count the total streams by month
DT.monthly_streams_per_source[, monthly_total_streams := sum(streams), by="month"]
DT.monthly_streams_per_source[, monthly_total_streams_per_group := sum(streams), by=monthGroup]
DT.monthly_streams_per_source[, perc_of_monthly_total_streams := as.perc(streams / monthly_total_streams)]
DT.monthly_streams_per_source[, perc_of_monthly_total_streams_per_group := as.perc(streams / monthly_total_streams_per_group)]


## CREATE DT.hist_plot
sdCols <- monthGroup %>% c("monthly_total_streams", "monthly_total_streams_per_group", .)
DT.hist_plot <- DT.monthly_streams_per_source[, unique(.SD), keyby=list(month, days_of_data_per_month), .SDcols=sdCols]
DT.hist_plot[, avg_streams_per_day := monthly_total_streams / days_of_data_per_month]
DT.hist_plot[, avg_streams_per_day_per_group := monthly_total_streams_per_group / days_of_data_per_month]
DT.hist_plot[, avg_streams_per_day_100M := avg_streams_per_day / 1e8]
DT.hist_plot[, avg_streams_per_day_per_group_100M := avg_streams_per_day_per_group / 1e8]


## ----------  PLOT  -------------
"(i.e. how did the user 'hit play')"
title <- subtext("Percent of Monthly Streams Attributed to each Origination Source", "(Orchard + RED)")
xlab  <- "" # "Month of Stream"
P.Spotify_source_of_stream <- {
    ggLinegraph(DT.monthly_streams_per_source, x="month", y="perc_of_monthly_total_streams_per_group", color="source", xlab=xlab, title=title, facet_formula=facetOn(group, justFormula=TRUE), dotsize=FALSE) %>% 
    ggInsertLayer(after=0, geom_bar(data = DT.hist_plot, aes(x=month, y = avg_streams_per_day_per_group_100M), stat="identity", alpha=0.15, color="#AAAAAA"))
}; P.Spotify_source_of_stream





ggsave.out(P.Spotify_source_of_stream)
"~rsaporta/git/orch/data/SpotifyAPIV2/DT.monthly_streams_per_source-20150506_1803-70x4.RDS"

~/git/orch/plots/Spotify_API_V2/Spotify_source_of_stream.png"