lib(ggplot)
setScience("Albums_vs_Tracks", create=TRUE)


## data downloaded from looker:     https://theorchard.looker.com/x/TfRq569
f.in <- "~/gitData/orch/data/Albums_vs_Tracks/iTunes Tracks vs Albums by price.csv"
it <- fread(f.in)

it[, Month := as.Date(sprintf("%s-01", `MONTH Activity Month`))]
it[, `MONTH Activity Month` := NULL]

setnames(it, c("TRANSACTION Album Or Track", "TOTAL Gross", "ACCOUNTING Retail Price"), c("AvT", "Gross", "Price"))

it[, Price := abs(as.numeric(Price))]
it <- it[, list(Gross = sum(Gross)), by=list(AvT, Price, Month)]
it[, table(Price)]
it[Price == 0]

it[, table(Price)]

setkey(it, AvT, Price, Month)

it[, Delta := diffNA(Gross, scaled=TRUE), by=AvT]

AvTGraph <- function(y, ylab, yscale=if(y=="Gross") millions.y else if(y=="Delta") percent.y else scale_y_continuous, data=it) {
  ggplot(data=data, aes(x=Month, color=AvT, shape=AvT)) + geom_line(aes_string(y=y)) + legendbottom(TRUE) + match.fun(yscale)() + ylab(ylab) + xlab("")
}


P.G <- AvTGraph(y="Gross", ylab="Gross (in Millions)") + facet_grid(~.Price)
P.D <- AvTGraph(y="Delta", ylab="Change in Gross")
printToPDF(list(P.G, P.D), ncol=1, f.name="Albums vs Tracks by Price", dir="~/Plots", sub=orchardFootNote(), main="iTunes Gross Revenue since 2012")

# Removing Jan 2013.  If you want to do this, you have to recalculate the deltas too. 
# P.G2 <- AvTGraph(y="Gross", ylab="Gross (in Millions)", data=it[Month != as.Date("2013-01-01")])
# P.D2 <- AvTGraph(y="Delta", ylab="Change in Gross", data=it[Month != as.Date("2013-01-01")])
# printToPDF(list(P.G2, P.D2), ncol=1, f.name="Albums vs Tracks - removed Jan 2013", dir="~/Plots", sub=orchardFootNote(), main="iTunes Gross Revenue since 2012")


