  # -------------------------------------------------------------------------------------------------------------------------------------------------  #
  #  -----------------------------------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                                                    #
  #           File Name              :  gg_barChart_bygrp.r                                                                                            #
  #           Last Updated Funclist  :  19 Feb 2015,  1:05 PM (Thursday)                                                                               #
  #                                                                                                                                                    #
  #           Author Name            :  Rick Saporta                                                                                                   #
  #           Author Email           :  RickSaporta@gmail.com                                                                                          #
  #           Author URL             :  www.github.com/rsaporta                                                                                        #
  #                                                                                                                                                    #
  #           Packages Called        :  NA                                                                                                             #
  #           Packages Used via NS   :  NA                                                                                                             #
  #                                                                                                                                                    #
  #  -----------------------------------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                                                    #
  #   gg_barChart_bygrp      ( DT, x, y, fill, alpha=NULL, grp, scale=c("", "comma", "percent"), x.lab=x, y.lab=y                                      #
  #                            , title="", removeUnderscores=TRUE, hierarchies=list()                                                                  #
  #                            , addhline=identical(scale, "percent") )                                                                                #
  #   plotBarChartWithRatios ( DT.raw, ratioCol, valueCol, value.name="Gross Revenue", main="\n", sub=NULL                                             #
  #                            , f.name="Value_and_Ratio_Facet_Plots"                                                                                  #
  #                            , timeStamp.plotfile=getOption("timestamp.plotfile"), hierarchies=list()                                                #
  #                            , Grouping=makeFacetGroups(DT=DT.raw, min.size=min, hierarchies=hierarchies, valueCol.toExclude=valueCol, ...), min=1L  #
  #                            , ..., height.per.plot=4.2, width.per.plot=8, verbose=TRUE )                                                            #
  #                                                                                                                                                    #
  #                                                                                                                                                    #
  #                                                                 <END FUNCS>                                                                        #
  #  -----------------------------------------------------------------------------------------------------------------------------------------------   #
  # -------------------------------------------------------------------------------------------------------------------------------------------------  #

# gg_barChart_bygrp.r


gg_barChart_bygrp <- function(DT, x, y, fill, alpha=NULL, grp, scale=c("", "comma", "percent")
                                , x.lab=x, y.lab=y, title="", removeUnderscores=TRUE
                                , hierarchies=list(), addhline=identical(scale, "percent")) {
  lib(ggplot, quiet=FALSE)

    scale <- match.arg(scale)

    if (isTRUE(removeUnderscores)) {
      x.lab <- gsub("_", " ", x.lab)
      y.lab <- gsub("_", " ", y.lab)
      title <- gsub("_", " ", title)
    }

    ggplot(data=DT) + 
      geom_bar(stat="identity", aes_string(x=x, y=y, fill=fill, alpha=alpha)) + 
      coord_flip() + 
      scale_alpha_identity() +
      guides(alpha=FALSE) + 
      # angledtext(x=0, y=20) + 
      fontface.axis("Helvetica") + 
      {if (scale=="comma")
                  comma.y() } + 
      {if (scale=="percent")
                  percent.y() } + 
      {if (isTRUE(addhline))
          geom_hline(y=.5, alpha=.3, size=1/3, color="black") } + 
      relativetext(.72^length(grp), .42^length(grp)) + 
      legendbottom(notitle=TRUE) +
      facetOn(grp, hierarchies=hierarchies) + 
      labs(x=x.lab, y=y.lab, title=title)
}

# --------# --------# --------# --------# --------# --------# --------#

plotBarChartWithRatios <- function(   DT.raw
                                    , ratioCol
                                    , valueCol
                                    , value.name = "Gross Revenue"
                                    , main="\n", sub=NULL
                                    , f.name="Value_and_Ratio_Facet_Plots"
                                    , timeStamp.plotfile=getOption("timestamp.plotfile")
                                    , hierarchies=list()
                                    , Grouping=makeFacetGroups(DT=DT.raw, min.size=min, hierarchies=hierarchies, valueCol.toExclude=valueCol, ...)
                                    , min=1L, ..., height.per.plot=4.2, width.per.plot=8, verbose=TRUE) {
  ## valueCol : A measurement column, such as sales for the group
  ## ratioCol : A column with two values indicating group
  ## ratio will be calculated as how much of the total valueCol is attributable to each value of the ratioCol 
  ## value.name : What the valueCol represents. eg Gross Revenue; Units; Fans, etc
  ##
  ## main, sub : Plot Title


  ## -- This is an old note, which I trailed off in....
  ## If ratioCol is on the axis, then it makes 

  gnms <- names(Grouping)

  verboseMsg(verbose, "There are ", length(Grouping), " total groups. First is '", gnms[1L], "'  and last is  '", tail(gnms, 1), "'\nProcessing Group...", sep="", time=FALSE)

  Plots <- unlist(lapply(Grouping, function(grp) 
  {

      verboseMsg(verbose, sprintf("     * '%s'", gnms[sapply(Grouping, identical, grp)]), sep="", time=FALSE)

      ## Aggregate the pieces
      DT <- AggAndRatio(DT.raw, byCols=grp, ratioCol=ratioCol, valueCol=valueCol)

      ## if y is less than 

      ### ________________________________________________________________________________________ ###
      ### Flip the first column, to compensate for the coord_flip() that happens later.
      ### However (1) do NOT flip for date cols.  
      ###         (2) if we are also coloring by that column, flipping will also affect the colors.
      ###             therefore, first create a new column ('rat2') and use the new col as the coloring (this is ok, because no legend for coloring)

          ## grab the first element in group. This will be the x-value (which will be flipped to y axis)
          g1 <- grp[[1]]

          ## Check if it is the same as ratioCol, which we'll use for coloring 
          if (g1 == ratioCol) {
              rat2 <- paste0(ratioCol, ".2")
              DT[, c(rat2) := get(ratioCol) ]
              ratioCol <- rat2
          }
          ## Check if it is not a date-like column.  Then cehck if it is a character of factor
          #OLD: if (! tolower(g1) %in% c("month", "year", "date", "day") ) {
          if (! any(sapply(c("month", "year", "date", "day"), grepl, g1, ignore.case=TRUE)) ) {
            if (is.character(g1) || is.factor(g1))
              DT[, c(g1) := reverseFactor(get(g1))]
          }
      ### ________________________________________________________________________________________ ###


      ## These are the plot variables for the two different plot types (Value & Ratio)
      Total_Propor_Lab <- setNames(nm=c("Revenue", "Ratio"), paste(c("Total", "Proportional"), value.name))

      y <- c(Revenue=valueCol, Ratio="proportions")
      y.lab <- if (value.name=="Gross Revenue") c("Gross Revenue", "Proportional Revenue") else Total_Propor_Lab
      y.lab <- list(NULL)
      scale <- c("comma", "percent")
      alpha <- list(NULL, "scaledAlpha")
      fill <- ratioCol

      ## if there is a country column in DT.raw, but not being used in DT, append "worldwid"
      countryTerms <- c("country", "continent")
      Append_WorldWide <- (any(countryTerms %in% tolower(names(DT.raw)) && !any(countryTerms %in% tolower(names(DT)))) )

      ## These are the titles
      title <- paste(Total_Propor_Lab, 
                      "\nby", 
                       if (length(grp)) pasteQand(grp, q=""), 
                       ## If there is no geographic breakdown, then it is worldwid
                       if (Append_WorldWide) " (Worldwide)", 
                       ## If there is no data-breakdown, then it is for all the periods
                       if (!any(c("Month") %in% grp)) sprintf("\nTotal for the %i month period", lunique(DT.raw[["Month"]]))
                      )

      ## The two plots are similar
      mapply(gg_barChart_bygrp
            , y=y, y.lab=y.lab, scale=scale, alpha=alpha, title=title
            , MoreArgs=list(DT=DT, x=grp[1L], fill=fill, grp=grp[-1L], hierarchies=hierarchies)
            , SIMPLIFY=FALSE
            )

    }
    ), recursive=FALSE)

  browser(expr=inDebugMode("ggplot"), text="Inside plotBarChartWithRatios(),\n\tafter the main `lapply` completed.")
  verboseMsg(verbose, "\nDone processing groups and creating plot objects.\nBeginning printToPDF.", time=FALSE)

  # png("~/Desktop/test.pdf")
  # for (i in seq(Plots)) {
  #   cat(sprintf(" %2i)   Grouping[[%2i]]      %-15s  \n", i, ceiling(i/2), names(Plots)[[i]]))
  #   print(Plots[[i]])
  # }
  # dev.off()

  ## Write to PDF.  The Output of this function will be the full name of the file where it will be saved to
  f.out <- printToPDF(Plots, f.name=f.name, ncol=2, main=main, sub=sub, timeStamp.plotfile=timeStamp.plotfile, height.per.plot=height.per.plot, width.per.plot=width.per.plot, verbose=verbose)

  ## Add the file as an attribute
  f.out <- gsub(path.expand("~"), "~", f.out)
  attr(Plots, "f.out") <- f.out

  ## Use invisible, otherwise, it will plot each element
  return(invisible(Plots))
}


