  # -------------------------------------------------------------------------------------------------------------------------  #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #           File Name              :  ggBarchart2.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                                                                                     #
  #                                                                                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  #                                                                                                                            #
  #   ggBarchart2        ( DT, x, y=NULL, fill, byCols=key(DT), yShouldSumToOneByGroup=FALSE                                   #
  #                        , position=c("dodge", "stack"), facet.x=".", facet.y=".", ylims=NULL, width=0.5                     #
  #                        , stat=c("identity", "bin"), xlab=gg_cleanColumnName(x), ylab=gg_cleanColumnName(y)                 #
  #                        , title="", legend=c("right", "bottom", "top", "left", "off"), legend_title_off=FALSE               #
  #                        , legend_font_size_rel=0.9 )                                                                        #
  #                                                                                                                            #
  #                                                                                                                            #
  #                                                     <END FUNCS>                                                            #
  #  -----------------------------------------------------------------------------------------------------------------------   #
  # -------------------------------------------------------------------------------------------------------------------------  #

## ggBarchart2.r


## EXAMPLE
if (FALSE) {

  {
    ggBarchart2(
        DT = copy(DT.bi_acc_with_act_date)
      , x = "months_back"
      # , y = "PercUnits_byGrp_AccountingMonth"
      , y = NULL
      # , fill = "accounting_month"
      , fill = "label_sc_group"
      , byCols = kCols.acc
      , yShouldSumToOneByGroup = TRUE
      , position = c("dodge", "stack")
      # , facet.x = c("store_name", "transac_type_abbr")
      , facet.x = c("accounting_month", "store_name")
      , facet.y = "."
      , ylims = c(0, ifelse(position == "dodge", 1.05, 4.05))
      , width = .5
      , stat = "bin" # "identity"
      , geom=c("bar", "density")
      # , legend = "off"
      , legend = "right"
      )
  }

    + gg_hline(1, size=.4) +  + scale_y_log10() # percent.y(lim=c(0, ymax))
}



ggBarchart2 <- function(
    DT
  , x
  , y = NULL
  , fill
  , color=fill
  , alpha=1
  , byCols = key(DT)
  , geom=c("bar", "density")
  , yShouldSumToOneByGroup = FALSE
  , position = c("dodge", "stack")
  , facet.x = "."
  , facet.y = "."
  , ylims = NULL
  , width = .5
  , stat = c("identity", "bin")
  , xlab = gg_cleanColumnName(x)
  , ylab = gg_cleanColumnName(y)
  , title = ""
  , legend = c("right", "bottom", "top", "left", "off")
  , legend_title_off = FALSE
  , legend_font_size_rel = 0.9
  , label = NULL
  , label_text_Size = 8
  , labelface = c("plain", "bold", "italic", "bolditalic")
  , convertToNumeric=TRUE
  , ...
) {

  geom <- match.arg(geom)

  ## Check that none of the args are names in DT
  if (any(c(x, y, fill, color, alpha) %in% c("fill", "color", "x", "y")))
    stop ("Do not use names like x, y, color, fill for column names with ggBarchart2")

  lib(ggplot, quiet=FALSE)

  position <- match.arg(position)
  stat     <- match.arg(stat)

  if (!is.null(label))
    if (!label %in% names(DT))
      stop ("label must be a name of DT")

  if (stat == "bin" && !is.null(y)) {
    warning ("y should be set to NULL or blank when using stat='bin'")
    y <- NULL
    if (missing(ylab))
      ylab <- "count" 
  }

  force(xlab)
  force(ylab)

  if (FALSE) {
    ##   Basic Plot for a few Stores   ##
    DT <- DT[store_name %in% main_stores] [accounting_month >= "2014-02-01"]
    DT <- DT[country_code %in% country_code.using]
    # DT.plot <- DT.plot[transac_type_abbr %in% c("DV", "UT")]
  }

  ## Confirm:  Proabilities for the group sum to 1
  if (yShouldSumToOneByGroup && !is.null(y))
    sumsToOne(DT, y, by=byCols, na.rm=TRUE)

  if (!is.null(fill)) {
    expected_values <- if (is.factor(DT[[fill]])) levels(DT[[fill]]) else unique(DT[[fill]])
    if (stat == "identity" & position == "dodge") {
      y.filler        <- NA_real_
      nms.filledcols <- c(fill, y)
      DT.plot.filled <- 
        DT[, {
                sc.toadd <- setdiff(expected_values, get(fill));
                ll <- list( c(as.character(get(fill)), sc.toadd)
                          , if(!is.null(y)) c(get(y), rep(y.filler, length(sc.toadd)))
                          )
                setattr(ll, "names", c(fill, y))
                ll[seq_along(nms.filledcols)]
              }, keyby=c(setdiff(c(byCols, x, facet.x, facet.y, label), c(fill, ".")))]
    } else 
      DT.plot.filled <- copy(DT)

    ## Convert to factor
    {
      if (fill == "label_sc_group")
        makeSCFactor_(DT.plot.filled, sccol=fill)
      else if (fill == "store_name")
        makeStoresFactor_(DT.plot.filled, storeCol=fill)
      else if (is.date_or_time(DT[[fill]]))
        DT.plot.filled[, (fill) := factor(as.character(get(fill)), levels=as.character(expected_values))]
      else 
        DT.plot.filled[, (fill) := factor(get(fill), levels=as.character(expected_values))]
    }
  } else 
    DT.plot.filled <- copy(DT)


  if (!is.factor(DT.plot.filled[[x]]))
    DT.plot.filled[, (x) := factor(get(x))]


  ## convert x to numeric
  if (convertToNumeric && !is.numeric(DT.plot.filled[[x]])) {
    converted <- as.num.as.char(DT.plot.filled[[x]], TRUE)
    NAs.introduced <- is.na(converted) & !is.na(DT.plot.filled[[x]])
    if (!any(NAs.introduced)) {
      DT.plot.filled[, (x) := converted]
    }
  }


  if (geom == "density") {
    if (missing(color) && !is.null(fill))
      color <- fill

    if (!is.numeric(DT.plot.filled[[x]])) {
      stop("When using geom_density, x ('", x, "') must be numeric. It is ", class(DT.plot.filled[[x]])[[1]], ".")
    }
  }


  geom_func <- match.fun(sprintf("geom_%s", geom))
  # P <- 
  #   ggplot(data=DT.plot.filled, aes_string(x=x, y=y, fill=fill, color=color)) + 
  #      geom_func(stat=stat, position=position, width=width, alpha=alpha)   +
  #      relativetext(x=1, y=.7) + 
  #      labs(x=xlab, y=ylab, title=title)

  if (!is.null(fill))
    P <- ggplot(data=DT.plot.filled, aes_string(x=x, y=y, fill=fill, color=color))
  else
    P <- ggplot(data=DT.plot.filled, aes_string(x=x, y=y))

  P <- P + geom_func(stat=stat, position=position, width=width, alpha=alpha)   +
       relativetext(x=1, y=.7) + 
       labs(x=xlab, y=ylab, title=title)

  ## Set Legend
  {
    legend <- match.arg(legend)
    if (legend == "off")
        P <- P + theme(legend.position="none")
    else if (isTRUE(legend_title_off))
          P <- P + theme(legend.position=legend, legend.text=element_text(size=rel(legend_font_size_rel)), legend.title = element_blank())
    else 
          P <- P + theme(legend.position=legend, legend.text=element_text(size=rel(legend_font_size_rel)))
  }

  if (!(identical(facet.x, ".") && identical(facet.y, ".")))
    P <- P + facet_grid(as.formula(sprintf("%s ~ %s", pasteC(facet.x, C="+"), pasteC(facet.y, C="+"))))

  if (!is.null(fill) && fill == "label_sc_group")
     P <- P + fill_by_dict("dict.colors.sc")

  if (!is.null(label)) {
    labelface <- match.arg(labelface)
    P <- P + geom_text(aes_string(label=label), size=label_text_Size, fontface=labelface, position="dodge")
  }

  # DT <- DT.plot.filled
  # rm(DT.plot.filled)
  # do.call(gg_GenericProcessing, collectArgs(), quote=TRUE)

  return(P)
}


