Chart <- function(x=NULL, by=NULL, y=NULL, data=d, filter=NULL,

        type=c("bar", "radar", "bubble", "dot", "pie", "icicle", "treemap"),
        hole=0.65,  # pie chart
        radius=0.35, power=0.5,  # bubble chart
        segments_x=NULL, segments_y=NULL, pt_size=1,
        origin_x=NULL, origin_y=NULL, # dot chart

        stat=c("mean", "sum", "sd", "deviation", "min", "median", "max"),
        stat_x=c("count", "proportion"),

        facet=NULL, n_row=NULL, n_col=NULL, aspect="fill",

        horiz=FALSE, sort=c("0", "-", "+"),
        beside=FALSE, stack100=FALSE,
        gap=NULL, scale_y=NULL, one_plot=NULL,

        theme=getOption("theme"),
        fill=NULL,
        color=getOption("bar_color_discrete"),
        transparency=getOption("trans_bar_fill"),
        fill_split=NULL, fill_scaled=FALSE, fill_chroma=75,

        labels=c("%", "input", "prop", "off"),
        labels_position=c("in","out"),
        labels_color="white",
        labels_size=0.90,
        labels_decimals=NULL,
        labels_cut=NULL,

        xlab=NULL, ylab=NULL, main=NULL, sub=NULL,
        lab_adjust=c(0,0), margin_adjust=c(0,0,0,0),
        pad_y_min=0, pad_y_max=0,

        rotate_x=getOption("rotate_x"), rotate_y=getOption("rotate_y"),
        break_x=NULL, offset=getOption("offset"),
        axis_fmt=c("K", ",", ".", ""), axis_x_pre="", axis_y_pre="",
        label_max=100,

        legend_title=NULL, legend_position="right_margin",
        legend_labels=NULL, legend_horiz=FALSE,
        legend_size=NULL, legend_abbrev=10, legend_adjust=0,

        add=NULL, x1=NULL, y1=NULL, x2=NULL, y2=NULL,

        quiet=getOption("quiet"), do_plot=TRUE, 
        use_plotly=getOption("lessR.use_plotly"),
        pdf_file=NULL, width=6.5, height=6,
        digits_d=NULL,

        eval_df=NULL, fun_call=NULL, ...) {


  if (is.null(fun_call)) fun_call <- match.call()

  mc <- match.call()
  .mc_nms <- names(mc)
  y.is.named <- "y" %in% .mc_nms

  # Note: if fill contains getColors() call, fill already evaluated
  fill.name <- deparse(substitute(fill))

  if (length(type) == 1 && type == "sunburst")
    type <- "pie"
  else
    type <- match.arg(type)

  stat.miss <- missing(stat)
  if (stat.miss) stat <- NULL
  if (!is.null(stat[1])) stat <- match.arg(stat)  # if condition for shiny
  stat_x <- match.arg(stat_x)

  options(xname = NULL)
  options(yname = NULL)
  options(byname = NULL)

  if ("facet2" %in% .mc_nms) {
    cat("\n"); stop(call.=FALSE, "\n------\n",
      "parameter  facet2  not applicable to Chart\n\n")
  }

  facet.miss <- missing(facet)

  if (!is.null(pdf_file) &&  type != "bar") {
    cat("\n"); stop(call.=FALSE, "\n------\n",
      "Saving PDF files only works for bar charts.\n\n")
  }

  if (type == "bubble"  &&  !facet.miss) {
      cat("\n"); stop(call.=FALSE, "\n------\n",
        "The  facet  option is not available for bubble plots.\n\n")
  }
  if (type != "dot") {  # for now, goes to XY(), where this is also listed
    if (!quiet && use_plotly && !(type == "bar" && !facet.miss)) {
      txt <- "[Interactive chart from the Plotly R package (Sievert, 2020)]"
      cat(txt, "\n\n")
    }
  }

  labels_size.miss <- missing(labels_size)
  if (!facet.miss && labels_size.miss) labels_size <- .85


# old stuff ---------------------------------------------------------------

  # Check for removed parameters. Uses .mc_nms (names(match.call())) defined
  # at the top of the function — avoids evaluating expressions prematurely.
  if ("rows" %in% .mc_nms) {
    stop(call. = FALSE, "\n------\n",
         "Parameter  rows  has been removed.\n",
         "Use  filter  instead, e.g., filter = (Age > 30)\n\n")
  }
  if ("n_cat" %in% .mc_nms) {
    stop(call. = FALSE, "\n------\n",
         "Parameter  n_cat  has been removed.\n",
         "Convert categorical integer variables to factors instead:\n",
         "  e.g., d$Item1 <- factor(d$Item1)\n\n")
  }
  if ("value_labels" %in% .mc_nms) {
    stop(call. = FALSE, "\n------\n",
         "Parameter  value_labels  has been removed.\n",
         "Convert categorical integer variables to factors instead:\n",
         "  e.g., d$Item1 <- factor(d$Item1, levels=1:3,\n",
         "         labels=c(\"Disagree\", \"Neutral\", \"Agree\"))\n\n")
  }

  if (deparse(substitute(fill)) == "(count)") {
    message(">>> Now set to TRUE the more general parameter:  fill_scale.\n\n")
    fill <- NULL
  }

  dots <- list(...)
  n.values <- 0
  if (length(dots) > 0) {
    for (i in seq_along(dots)) {
      if (grepl("values", names(dots)[i], fixed=TRUE)) {
        n.values <- n.values + 1
        if (n.values == 1)
          message(">>> Parameters  values, values_color, etc. now ",
                  "renamed to:  labels, labels_color, etc.\n",
                  "    Old parameter names will stop working in the future.\n")
        if (names(dots)[i] == "values") labels <- dots[[i]]
        if (names(dots)[i] == "values_color") labels_color <- dots[[i]]
        if (names(dots)[i] == "values_size") labels_size <- dots[[i]]
        if (names(dots)[i] == "values_digits") labels_decimals <- dots[[i]]
        if (names(dots)[i] == "values_position") labels_position <- dots[[i]]
        if (names(dots)[i] == "values_cut") labels_cut <- dots[[i]]
      }
      if (names(dots)[i] == "addtop") pad_y_max <- dots[[i]]
      if (names(dots)[i] == "add_top") pad_y_max <- dots[[i]]
      if (names(dots)[i] == "stat_yx") stat <- dots[[i]]
      if (grepl(".", names(dots)[i], fixed=TRUE)) {
        pnm <- gsub(".", "_", names(dots)[i], fixed=TRUE)  # dot to _
        assign(pnm, dots[[i]])
      }
    }
  }

  if (!is.null(stat)) if (stat[1] == "proportion") {
    cat("\n"); stop(call.=FALSE, "\n------\n",
      "now use parameter  stat_x  for \"proportion\" \n",
      "  \"proportion\" only applies when there is no y numeric variable\n\n")
  }


  Trellis <- !facet.miss && type == "bar"


# set variables -----------------------------------------------------------

  trans <- transparency

  if (fill_scaled  &&  is.null(fill_split)) fill_split <- 0

  if (nzchar(axis_fmt[1])) axis_fmt <- match.arg(axis_fmt)

  fill.miss <- missing(fill)
  color.miss <- missing(color)
  transparency.miss <- missing(transparency)
  horiz.miss <- missing(horiz)
  y.miss <- missing(y)
  by.miss <- missing(by)
  main.miss <- missing(main)
  for (i in seq_along(color)) if (color[i] == "off") color[i] <- "transparent"

  if (type == "dot" && !by.miss) {
    cat("\n"); stop(call.=FALSE, "\n------\n",
      "The  by  variable is not meaningful for dot charts. Do a bar chart.\n\n")
  }

  sort.miss <- missing(sort)
  sort <- match.arg(sort)
  labels.miss <- missing(labels)
  labels <- match.arg(labels)
  labels_position <- match.arg(labels_position)


# set some parameter values -----------------------------------------------

  proportion <- stat_x[1] == "proportion"

  if (horiz) sort <- switch(sort, "+" = "-", "-" = "+", "0" = "0")

  if (missing(break_x))
    break_x <- !horiz && rotate_x == 0

  xlab.adj <- lab_adjust[1];   ylab.adj <- lab_adjust[2]
  tm.adj <- margin_adjust[1];  rm.adj <- margin_adjust[2]
  bm.adj <- margin_adjust[3];  lm.adj <- margin_adjust[4]

  lm.adj <- lm.adj + .1  # pull these margins back a bit for bc
  bm.adj <- bm.adj + .1

  if (missing(labels_color)) {
    labels_color <- "white"
    if (labels_position == "out") labels_color <- getOption("axis.text.color")
  }

  # ensure valid parameter values
  # exception: fill=c(lo, hi) with fill_split is the user-defined divergent scale —
  # pass fill.miss=TRUE to the validator so it doesn't block this combination
  fill.miss.valid <- fill.miss || (!fill.miss && !is.null(fill_split) && length(fill) == 2L)
  .bcParamValid(y.miss, by.miss, facet.miss, Trellis, sort,
                fill_split, fill_scaled, fill_chroma, theme,
                fill.miss.valid, labels_position, stat.miss)



# data frame stuff --------------------------------------------------------

  data.miss <- missing(data)

  # let deprecated mydata work as default
  dfs <- .getdfs()
  mydata.ok <- FALSE
  if (!is.null(dfs)) {
    if ("mydata" %in% dfs  &&  !("d" %in% dfs)) {
      d <- mydata
      rm(mydata)
      df.name <- "mydata"
      mydata.ok <- TRUE
      options(dname = df.name)
    }
  }

  # get name of data table
  # df.name is NULL if from shiny interact(), not from user-written shiny code
  if (!mydata.ok) {
    df.name <- deparse(substitute(data))
    options(dname = df.name)
  }

  shiny <- FALSE
  if (!is.null(sys.call(-1)))  # is NULL when called directly from R console
    if (sys.call(-1) == "renderPlot()") {  # from shiny, user or interact()
      shiny <- TRUE
      data <- eval(substitute(data), envir=parent.frame())
    }

  # if a tibble, convert to data frame
  if (!shiny) {
    if (exists(df.name, envir=.GlobalEnv)) {
      if (any(grepl("tbl", class(data), fixed=TRUE)))
        data <- data.frame(data)
    }
  }
  else  # no check for existence of df.name
    if (any(grepl("tbl", class(data), fixed=TRUE)))
      data <- data.frame(data)

  x.name <- deparse(substitute(x), width.cutoff = 120L)
  # deparse of a vector (e.g. from Shiny with data=NULL) produces multiple strings
  # use xlab as the display name instead, falling back to "x"
  if (length(x.name) > 1L)
    x.name <- if (!is.null(xlab) && nzchar(xlab)) xlab else "x"
  options(xname = x.name)

  # validate x.name is not an expression; global iff user set data=NULL
  # skip validation when called from Shiny with pre-extracted vectors (data=NULL)
  if (!is.null(x.name) && !(shiny && df.name == "NULL")) .in.global(x.name, quiet)
  x.in.global <- if (shiny && df.name == "NULL") TRUE
                 else .resolve.var(x.name, df.name, role="x", fun.name="Chart")
  if (!x.in.global) {
    # force evaluation (not lazy) if data not specified, relies on default d
    if (data.miss) {
      if (!mydata.ok) .nodf(df.name)  # check to see if df exists
      # the 1.201 comes from Shiny, need to reset
      # l.cex and l.axc are set in interact() before shiny run
      if (getOption("lab_cex") == 1.201) {
       if (getOption("l.cex") != 1.201) {
          style(lab_cex=getOption("l.cex"))
          style(axis_cex=getOption("l.axc"))
        }
        else
          style()
      }
    }
  }

  eval_df <- !x.in.global


# subset filter -----------------------------------------------------------

  if (!missing(filter)) {

    if (x.in.global) {
      cat("\n"); stop(call.=FALSE, "\n------\n",
        "Parameter  filter  not applicable if no data frame\n\n")
    }

    txt <- .filter(deparse(substitute(filter)))

    # get r, label each row as TRUE or FALSE
    intYN <- try(eval(parse(text = txt)), silent = TRUE)
    if (is.numeric(intYN)) {
      r <- rep(FALSE, nrow(data))
      r[intYN] <- TRUE
    }
    else {
      r <- eval(str2expression(txt), envir=data, enclos=parent.frame())
      r <- r & !is.na(r)  # set missing for a row to FALSE
    }

    nr.before <- nrow(data)
    if (any(r))
      data <- data[r,,drop=FALSE]
    if (!quiet) {
      cat("\nfilter: ",  txt, "\n-----\n")
      cat("Rows of data before filtering: ", nr.before, "\n")
      cat("Rows of data after filtering:  ", nrow(data), "\n\n")
    }
  }  # end filter


# establish if a data frame, otherwise identify variable(s)----------------
  # x can be missing entirely, with a data frame passed instead
  # if x a vector, then x.name not in data, but also not in global

  x.call <- NULL

  if (is.null(x.name)) x.name <- ""
  if (x.name %in% c("row_names", "row.names")) {
    # retain order of row names, otherwise will be alphabetical
    x.call <- factor(row.names(data), levels=row.names(data))
    if (is.null(xlab)) xlab <- ""  # unless specified, drop the axis label
  }

  else if (!missing(x)) {

    if (!x.in.global) {
      if (eval_df) {
        if (!mydata.ok) if (!shiny) .nodf(df.name)  # check to see if df exists
        .xcheck(x.name, df.name, names(data))  # x-vars in df?
      }

      data.vars <- as.list(seq_along(data))
      names(data.vars) <- names(data)
      ind <- eval(substitute(x), envir=data.vars)  # col num of each var
      if (length(ind) > 1) data <- data[, ind]  # x a vars list, no by vars
      if (length(ind) == 1) x.call <- eval(substitute(data$x))  # x is 1 var
    }

    else {  # x is in the global environment (vector, matrix or data frame)
      if (is.data.frame(x))  # x a data frame
        data <- x
      else {  # x a vector or matrix in global
        if (exists(x.name, envir=.GlobalEnv)) if (is.matrix(x)) {
          x.name <- xlab
          xlab <- NULL
          by.name <- legend_title
          options(xname = x.name)
          options(byname = by.name)
        }
        x.call <- x
        if (is.function(x.call)) x.call <- eval(substitute(data$x))
      }
    }

    # if read from console with text parameter can insert extra space at front
    if (is.factor(x.call))
      if (nchar(levels(x.call)[1]) > 5)
        levels(x.call) <- trimws(levels(x.call), which="left")
    else if (is.character(x.call))
      if (nchar(x.call[1]) > 5) x.call <- trimws(x.call, which="left")
  }  # !missing x


  # -------------------------------------------------
  # -------------------------------------------------
  # x is a single var, not a data frame or a var list
  if (!is.null(x.call)) {


# --- resolve `by`, which can be a vector ---------------------------------

    # shared helper: retrieve column from data frame or global environment
    caller_env <- parent.frame()
    get_col <- function(nm) {
      if (df.name != "NULL") {
        .xcheck(nm, df.name, names(data))
        return(data[[nm]])
      } else {
        return(get(nm, envir = caller_env))
      }
    }

    if (!by.miss) {
      by_expr <- substitute(by)
      by_vars <- all.vars(by_expr)

      if (length(by_vars) == 0L) {
        # already-evaluated object (rare); coerce to factor
        by.call <- try(eval(by_expr, envir = parent.frame()), silent = TRUE)
        if (inherits(by.call, "try-error")) by.call <- NULL
        if (!is.null(by.call) && !is.data.frame(by.call)) {
          if (!is.factor(by.call)) by.call <- factor(by.call)
          by.name <- deparse(by_expr)
        } else if (is.data.frame(by.call)) {
          for (nm in names(by.call))
            if (!is.factor(by.call[[nm]])) by.call[[nm]] <- factor(by.call[[nm]])
          by.name <- paste(names(by.call), collapse = " - ")
        }
      }
      else if (length(by_vars) == 1L) {
        by.call <- get_col(by_vars[1])
        if (!is.factor(by.call)) by.call <- factor(by.call)
        by.name <- by_vars[1]
      }
      else {
        # vector of by's -> data.frame of factors
        by_df <- lapply(by_vars, get_col)
        by_df <- lapply(by_df, function(v)
                        if (is.factor(v)) droplevels(v) else factor(v))
        by.call <- as.data.frame(by_df, check.names = FALSE)
        names(by.call) <- by_vars
        by.name <- paste(by_vars, collapse = " - ")
      }
      options(byname = by.name)

      # by  should be categorical or integer variable with <= 10 unique values
      v <- if (is.data.frame(by.call)) by.call[[1]] else by.call
      if (!is.character(v) && !is.factor(v) && !.is.num.cat(v, n_cat = getOption("n_cat"))) {
        warning("\n\nThe 2nd argument is by= , which should be categorical. \n",
                by.name, " likely is not categorical. Maybe set this\n",
                "variable to  y= , which should be a numerical variable.\n\n")
      }

      if (labels_position == "out"  &&  !beside) {
        stop(call.=FALSE, "\n------\n",
          "labels_position=\"out\" not meaningful for a  by  variable\n",
          "  without beside=TRUE\n\n")
      }
    }  # end not by.miss 

    else {
      by.call <- NULL
      by.name <- NULL
    }


# --- resolve y ------------------------------------------------------

    y.name <- deparse(substitute(y), width.cutoff = 120L)  # can be NULL
    options(yname = y.name)

  # process row.names if specified, applicable to type="dot"
  if (y.name %in% c("row_names", "row.names")) {
    # retain order of row names, otherwise will be alphabetical
    y.call <- data.frame(factor(row.names(data), levels=row.names(data)))
    if (is.null(ylab)) ylab <- ""  # unless specified, drop the axis label
  }

  else {
    # validate y.name is not an expression; global iff user set data=NULL
    if (!is.null(y.name) && !(shiny && df.name == "NULL")) .in.global(y.name, quiet)
    y.in.global <- if (shiny && df.name == "NULL") TRUE
                   else .resolve.var(y.name, df.name, role="y", fun.name="Chart")
    eval_df <- !y.in.global

    # if not missing, then must be aggregated data
    if (!missing(y)) {  # assign y.call from data or from global
      y.name <- deparse(substitute(y))

      # see if var exists in data frame, if y not in global Env or fun call
      if (eval_df)
        if (!y.in.global) .xcheck(y.name, df.name, names(data))
      if (!y.in.global) {
        data.vars <- as.list(seq_along(data))
        names(data.vars) <- names(data)
        y.ind <- eval(substitute(y), envir = data.vars)
        if (length(y.ind) > 1L) {
          y.call <- data[, y.ind, drop = FALSE]   # multi-column: data frame
        } else {
          y.call <- eval(substitute(data$y))       # single column: vector
        }
      } else {  # vars that are function names get assigned to global
        y.call <- y
        if (is.function(y.call)) y.call <- eval(substitute(data$y))
      }
      if (is.null(digits_d)) digits_d <- .max.dd(
        if (is.data.frame(y.call)) unlist(y.call) else y.call)
    }  # end !missing(y)

    else {
      y.name <- "Count"
      y.call <- NULL
      if (is.null(digits_d)) digits_d <- 0  # y will be counts
    }
  }  # end !row_name


# --- resolve facet --------------------------------------------------

  facet.call <- NULL
  facet.name <- NULL

  if (!missing(facet)) {
    facet_expr <- substitute(facet)
    facet_vars <- all.vars(facet_expr)

    if (length(facet_vars) == 1L) {
      # single facet variable — resolve to a factor vector
      v <- get_col(facet_vars[1L])
      facet.call <- if (is.factor(v)) droplevels(v) else factor(v)
      facet.name <- facet_vars[1L]
    } else {
      # multiple facet variables — resolve to a data frame of factors
      fac_list <- lapply(facet_vars, function(nm) {
        v <- get_col(nm)
        if (!is.factor(v)) v <- factor(v)
        droplevels(v)
      })
      facet.call <- as.data.frame(fac_list, stringsAsFactors = FALSE)
      names(facet.call) <- facet_vars
      facet.name <- paste(facet_vars, collapse = ", ")
    }

    # use the legacy option name expected by .bar.lattice()
    options(facet1name = facet.name)
  }

  # save pre-aggregation data for .hier.plotly() hover tooltips —
  # done once here after all four variables are resolved and before any aggregation
  if (type %in% c("pie", "icicle", "treemap", "sunburst")) {
    x.raw     <- x.call
    by.raw    <- by.call
    y.raw     <- y.call
    facet.raw <- facet.call
  }


# ------------------------------------------------------------
# -----------  x, y, by, and facet variables established -----
# ------------------------------------------------------------

# suggestions -------------------------------------------------------------

    txsug <- ""
    if (getOption("suggest") && !quiet  && type != "dot") {
      # function call, with last ) removed for suggestions
      fncl <- .fun_call.deparse(fun_call)  # class call to class character
      fncl <- gsub(")$", "", fncl)  # get function call less closing )
      fncl <- gsub(" = ", "=", fncl)
      txsug <- ">>> Suggestions  or  enter: style(suggest=FALSE)"

      if (!is.null(by.call)) {
        by_sug <- if (grepl(" - ", by.name, fixed=TRUE))
                    paste0("c(", gsub(" - ", ", ", by.name, fixed=TRUE), ")")
                  else by.name
        fc <- paste("Chart(", x.name, ", by=", by_sug, sep="")
      } else
        fc <- paste("Chart(", x.name, sep="")

      if (!grepl("radar", fncl)) {
        txt <- ", type=\"radar\""  # many options"
        cmt <- "  # Plotly radar chart"
        txsug <- paste(txsug, "\n", fc, txt, ")", cmt, "\n", sep="")
      }

      if (!grepl("treemap", fncl)) {
        txt <- ", type=\"treemap\""  # many options"
        cmt <- "  # Plotly treemap chart"
        txsug <- paste(txsug, fc, txt, ")", cmt, "\n", sep="")
      }

      if (!grepl("pie", fncl)) {
        txt <- ", type=\"pie\""  # many options"
        cmt <- "  # Plotly pie/sunburst chart"
        txsug <- paste(txsug, fc, txt, ")", cmt, "\n", sep="")
      }

      if (!grepl("icicle", fncl)) {
        txt <- ", type=\"icicle\""  # many options"
        cmt <- "  # Plotly icicle chart"
        txsug <- paste(txsug, fc, txt, ")", cmt, "\n", sep="")
      }

      if (!grepl("bubble", fncl)) {
        txt <- ", type=\"bubble\""  # many options"
        cmt <- "  # Plotly bubble chart"
        txsug <- paste(txsug, fc, txt, ")", cmt, "\n", sep="")
      }

      txsug <- paste(txsug, "\n")

       class(txsug) <- "out"
       print(txsug)
    }  # end suggest


  # is a numerical, continuous variable in the second or by position?
  n.by <- if (is.null(by.call)) 0
          else if (is.data.frame(by.call)) nrow(unique(by.call))
               else length(unique(by.call))


  if (is.null(by.call)) by.name <- NULL
  if (!is.null(by.call) && is.numeric(by.call) && !y.is.named) {
    if (!stat.miss && y.miss) {
      cat("\n"); stop(call.=FALSE, "\n","------\n",
        "Parameter  stat  requires a numerical y-variable to transform.\n\n",
        "Perhaps you have a numerical variable that you wish to transform.\n",
        "If so, then you now need to provide the label:  y = ", by.name, "\n\n",
        "Or, if the variable is the 2nd categorical variable in the analysis\n",
        "  then label as:  by = ", by.name, "\n")
    }
  }


# not pre-aggregated data -------------------------------------------------

    lx.u <- length(unique(x.call))
    lx <- if (is.data.frame(x.call)) nrow(x.call) else length(x.call)
    if (is.null(by.call))
      is.agg <- lx.u >= lx
    else {
      lby.u <- if (is.data.frame(by.call)) nrow(unique(by.call))
               else length(unique(by.call))
      lby <- if (is.data.frame(by.call)) nrow(by.call) else length(by.call)
      is.agg <- lx.u * lby.u >= lby
    }

  # set labels default for aggregated data 
    if (labels.miss && (!stat.miss || is.agg))
        labels <- if (beside) "%" else "input"


## ---- Missing data removal: x, y, by (possibly multi-column), facet ----

    # Save the full x.call and y.call before filtering — dot charts display
    # all category labels on the axis, with no dot where y is missing.
    x.call.all <- x.call
    y.call.all <- y.call

    # flatten multi-variable facet to a single interaction vector before
    # casewise missing removal — .drop_casewise_missing expects a vector
    if (is.data.frame(facet.call)) {
      facet.call <- factor(apply(facet.call, 1, paste, collapse = " / "))
    }

    # For multi-column y, collapse to a single logical NA-indicator vector
    # so .drop_casewise_missing() never sees a data frame — avoids tibble
    # recycling errors that occur when dplyr/tibble is loaded in session.
    y.for.cc <- if (is.data.frame(y.call) && ncol(y.call) > 1L)
      rowSums(is.na(y.call)) > 0  # TRUE where any column has NA
    else
      y.call

    cc <- .drop_casewise_missing(  # build data frame with relevant vars
      x.call    = x.call,
      y.call    = y.for.cc,
      by.call   = by.call,
      facet.call= facet.call
    )

    if (!is.null(cc) && !all(cc)) {

      # x.call: vector OR matrix/data.frame
      if (!is.null(x.call)) {
        if (is.matrix(x.call) || is.data.frame(x.call)) {
          x.call <- x.call[cc, , drop = FALSE]
        } else {
          x.call <- x.call[cc]
        }
      }

      # y.call: vector OR data.frame (multi-column y)
      if (!is.null(y.call)) {
        if (is.matrix(y.call) || is.data.frame(y.call)) {
          y.call <- y.call[cc, , drop = FALSE]
        } else {
          y.call <- y.call[cc]
        }
      }

      # by.call: vector OR matrix/data.frame
      if (!is.null(by.call)) {
        if (is.matrix(by.call) || is.data.frame(by.call)) {
          by.call <- by.call[cc, , drop = FALSE]
        } else {
          by.call <- by.call[cc]
        }
      }

      # facet.call: vector OR matrix/data.frame
      if (!is.null(facet.call)) {
        if (is.matrix(facet.call) || is.data.frame(facet.call)) {
          facet.call <- facet.call[cc, , drop = FALSE]
        } else {
          facet.call <- facet.call[cc]
        }
      }
    }


# check conditions when a y variable is present ---------------------------

    if (!is.null(y.call)) {  # a y variable present
      if (is.agg) {  # a summary table
        if (!stat.miss) { # stat specified but data already aggregated
          cat("\n"); stop(call.=FALSE, "\n------\n",
            "The data are a summary table, so do not specify a value of\n",
            "  stat  as the data aggregation has already been done\n\n")
        }
        if (sum(is.na(x.call)) > 0 ||
              sum(is.na(by.call)) > 0 ||
              sum(is.na(y.call)) > 0)   {
            cat("\n"); stop(call.=FALSE, "\n------\n",
              "When reading a summary table, missing data not allowed.\n\n")
        }
      }  # is a summary table
      else {
        if (!is.agg && stat.miss && type != "dot") {
          cat("\n"); stop(call.=FALSE, "\n------\n",
            "The data are not a summary (pivot) table, and you have a ",
            "numerical variable,\n",
            "    y = ", y.name, "\n",
            "so need to specify a value of  stat  to define the aggregation of\n",
            y.name, ", such as stat=\"mean\".\n\n")
        }
      }  # end is not a summary table
    }  # a y variable


# evaluate specified fill (NULL, numeric constant, or a variable) ---------

  if (!is.null(fill)) {
    if (length(fill.name) == 1) {
      if (exists(df.name, envir=.GlobalEnv))
        in.df <- fill.name %in% names(data)
      else
        in.df <- FALSE
    }
      else in.df <- FALSE
    # only works for y given, not tabulated
    if (in.df) {  # fill is a variable
    # need to aggregate cat var x and set fill.val to those limited values
    # currently, fill.val consists of all data values of variable fill
      fill.val <- data[[fill.name]]  # fill is a variable in data
      fill <- .getColC(fill.val, fill_name=fill.name)
      if (sort != "0") {
        srt.dwn <- sort == "-"
        fill <- fill[order(fill.val, decreasing=srt.dwn)]
      }
    }

    # evaluate getColors at the time of the function call
    # re-evaluate here by setting fill with the specified value of n
    if (substr(fill.name[1], 1, 9) == "getColors")
      fill <- .do_getColors(fill.name, lx.u)
  }  # end fill is present

  n.x <- length(unique(x.call))
  fill_palette <- if (is.null(fill)) .get_fill(theme)
                  else gsub("\"", "", fill.name)  # strip deparse quotes
  seq_pals <- c("gray", "grays", "grey", "greys", "blues", "greens",
                "reds", "purples", "oranges", "browns", "terrain")
  is_seq_fill <- tolower(fill_palette) %in% seq_pals ||
                 theme %in% c("gray", "white")
  if (is.null(fill)) {
    if (type == "bar" && n.by == 0) {
      fill <- NULL  # let bc_main set the theme default; avoids luminance gradient
    } else if (is_seq_fill && n.by > 0) {
      # sequential with by=: n.by colors spanning full range, lighter at bottom
      fill <- rev(.color_range(.get_fill(theme), n.by))
    } else if (type == "bar" && beside && n.by > 0) {
      # beside bar with by=: one color per by-level, not per x-level
      fill <- .color_range(.get_fill(theme), n.by)
    } else {
      fill <- .color_range(.get_fill(theme), max(n.x, n.by))
    }
  }


# Trellis plots for bar plots ---------------------------------------------

  if (Trellis && do_plot) {

    # facet2 not currently available
    .bar.lattice(x.call, facet.call, facet2=NULL, n_row, n_col, aspect,
                 proportion, fill, color, trans, size.pt=NULL,
                 xlab, ylab, main, rotate_x, offset,
                 axis_fmt, axis_x_pre, axis_y_pre,
                 width, height, pdf_file,
                 segments_x=NULL, breaks=NULL, T.type="bar", quiet)

    return(invisible(NULL))
  }


# set up pdf_file if needed -----------------------------------------------

  if (!is.null(pdf_file)) {
    if (!grepl(".pdf", pdf_file, fixed=TRUE))
      pdf_file <- paste(pdf_file, ".pdf", sep="")
    pdf(file=pdf_file, width=width, height=height, onefile=FALSE)
  }
  else {
    # only open a graphics device for bar charts (other types use plotly widgets)
    if (type == "bar" && df.name != "NULL")
        .opendev(pdf_file, width, height)
  }


# stat aggregation: y is present with raw data and stat not NULL ----------

  if (!is.agg) {
    if (!is.null(stat) && !is.null(y.call)) {  # y with stat

      ## ----- console stats BEFORE reducing data -------------------------
      if (!quiet) {
        txout <- ""
        ## only show the one-way numeric summary when there is
        ## truly only one variable (no by, no facet)
        if (is.null(by.call) && is.null(facet.call) &&
            !is.data.frame(y.call) && !is.matrix(y.call)) {
          options(yname = x.name)  # reverse x and y names, .ss.numeric
          options(xname = y.name)

          stats <- .ss.numeric(y.call, by = x.call, digits_d = digits_d,
                               brief = TRUE, y.name = x.name)
          txout <- stats$tx

          options(xname = x.name)  # reverse back
          options(yname = y.name)
        }

        class(txout) <- "out"
        output <- list(out_txt = txout)
        class(output) <- "out_all"
        print(output)
      }  # end !quiet


      ## ----- aggregate --------------------------------------------------
      is.agg <- TRUE

      # multi-column y (e.g. y=c(Pre,Post)): aggregate each column separately
      if (is.data.frame(y.call) && ncol(y.call) > 1L) {
        stat_fn <- switch(stat,
          mean     = function(z) mean(z, na.rm=TRUE),
          sum      = function(z) sum(z,  na.rm=TRUE),
          sd       = function(z) sd(z,   na.rm=TRUE),
          min      = function(z) min(z,  na.rm=TRUE),
          max      = function(z) max(z,  na.rm=TRUE),
          median   = function(z) median(z, na.rm=TRUE),
          mean  # default
        )
        x_grp  <- if (is.data.frame(x.call)) x.call[, 1L] else x.call
        agg_df <- as.data.frame(
          lapply(y.call, function(col) tapply(col, x_grp, stat_fn))
        )
        x.call <- factor(rownames(agg_df), levels=rownames(agg_df))
        y.call <- agg_df
        stat_cap <- paste0(toupper(substr(stat, 1L, 1L)),
                           substr(stat, 2L, nchar(stat)))
        if (is.null(ylab)) ylab <- paste(
          stat_cap, "of", paste(names(agg_df), collapse=" & "))
        y.name <- ylab
      } else {
        stat_out <- .stats(x.call, y.call, by.call, facet.call, stat, y.name)
        out <- stat_out$out  # aggregated data

        if (is.null(ylab)) {
          ylab   <- stat_out$ylab
          y.name <- ylab
        }

      # table already printed above
      if (is.null(by.call) && is.null(facet.call)) {  # 'out' is a named vector
        x.call <- factor(names(out))
        y.call <- as.vector(out)
      }

      else {  # by.call or facet.call is present, 'out' is a data.frame
        # build: y ~ group_cols + x

        ## all grouping columns (by + facet) are everything except x,y
        grp_cols <- setdiff(names(out), c("x", "y"))

        if (!quiet) cat("Summary Table for", ylab, "\n\n")

        if (!length(grp_cols)) {
          x.tbl.print <- xtabs(y ~ x, data = out)
        } else {
          form  <- reformulate(c(grp_cols, "x"), response = "y")
          x.tbl.print <- xtabs(form, data = out)
        }

        x.lbl <- .getlabels(main=main, lab_cex=getOption("lab_cex"))$xl
        if (!quiet) {
          .print_table(
            x.tbl    = x.tbl.print,
            x.name   = x.name,
            x.lbl    = x.lbl,
            by.name  = by.name,  # label string, not the columns
            y.name   = y.name,
            stat     = stat,
            digits_d = digits_d
          )
        }

        ## ----- Update x.call / by.call / facet.call / y.call ----------------
        ## After aggregation, downstream plotting should see the *reduced* data.

        x.call <- out[["x"]]
        y.call <- out[["y"]]

        ## how many by / facet variables did we start with?
        n_by <- if (is.null(by.call))
          0L
        else if (is.data.frame(by.call))
          ncol(by.call)
        else
          1L

        n_facet <- if (is.null(facet.call))
          0L
        else if (is.data.frame(facet.call))
          ncol(facet.call)
        else
          1L

        by_cols <- if (n_by > 0L)
          grp_cols[seq_len(n_by)]
        else
          character(0L)

        facet_cols <- if (n_facet > 0L)
          grp_cols[seq(from = n_by + 1L, length.out = n_facet)]
        else
          character(0L)

        ## by.call: NULL, vector, or data.frame depending on how many by vars
        if (!length(by_cols))
          by.call <- NULL
        else if (length(by_cols) == 1L)
          by.call <- out[[by_cols[1L]]]
        else
          by.call <- out[by_cols]

        ## facet.call: NULL, vector, or data.frame depending on how many facets
        if (!length(facet_cols))
          facet.call <- NULL
        else if (length(facet_cols) == 1L)
          facet.call <- out[[facet_cols[1L]]]
        else
          facet.call <- out[facet_cols]
      }
      }  # end single-column y stat aggregation
  }  # y is present for original data and stats not NULL


# else do table stats of counts -------------------------------------------

  else if (type != "bar") {  # do table of counts, done in bc.main for bar
    gl <- .getlabels(main=main, lab_cex=getOption("lab_cex"))
    x.name <- gl$xn; x.lbl <- gl$xl

    if (!quiet) {
      # build the 1-D / 2-D table strictly for console output & hover
      x.tbl.print <- .build_xtab(
        x        = x.call,
        y        = y.call,
        by       = if (!is.null(by.call)) by.call else facet.call,
        facet    = NULL,
        stat     = stat,
        is.agg   = is.agg,
        digits_d = digits_d
      )

      if (length(dim(x.tbl.print)) < 3) { # by not a vector
        .print_table(  # print 1-D or 2-D, in zzz_plotly
          x.tbl   = x.tbl.print,
          x.name  = x.name,
          x.lbl   = x.lbl,
          by.name = if (!is.null(by.call)) by.name
                    else if (!is.null(facet.call)) facet.name
                    else NULL,
          y.name  = if (!is.null(stat) && !is.null(y.call)) y.name else "Count",
          stat    = stat,
          digits_d = digits_d
        )
      }
    }  # end !quiet
  }  # end need to aggregate
  }  # end if (!is.agg)


# begin processing designated chart type ----------------------------------


  if (type == "bar") {
    bc <- .bc.main(x.call, y.call, by.call, stack100,
          fill, color, trans,
          fill_split, fill_scaled, fill_chroma, fill_palette, theme,
          horiz, gap, proportion, scale_y,
          xlab, ylab, main,
          label_max, beside,
          rotate_x, offset, 
          axis_fmt, axis_x_pre, axis_y_pre,
          break_x, sort,
          labels, labels_color, labels_size, labels_decimals,
          labels_position, labels_cut,
          xlab.adj, ylab.adj, bm.adj, lm.adj, tm.adj, rm.adj,
          pad_y_min, pad_y_max,
          legend_title, legend_position, legend_labels,
          legend_horiz, legend_size, legend_abbrev, legend_adjust,
          add, x1, x2, y1, y2, 80, do_plot, use_plotly, quiet,
          shiny, digits_d, ...)

    if (!is.null(pdf_file)) {
      dev.off()
      if (!quiet) .showfile(pdf_file, "BarChart")
    }

    return(invisible(bc))
  }


# Hierarchical chart -------------------------------------------------------

  else if (type %in% c("sunburst", "treemap", "icicle") ||
          (type == "pie" && !is.null(by.call))) {
    if (type == "pie") type <- "sunburst"

    ttl <- if (!main.miss && !is.null(main)) main[1]
           else if (main.miss) .plotly_build_title(
             x.name     = x.name,
             by.name    = if (!is.null(by.call)) by.name else NULL,
             facet.name = if (!is.null(facet.call)) facet.name else NULL,
             y.name     = if (!is.null(y.call)) y.name else NULL,
             stat       = if (!is.null(y.call)) stat   else NULL
           )
           else NULL   # main=NULL explicitly supplied — no title

    plt <- .hier.plotly(
      x.call=x.raw, by.call=by.raw, facet.call=facet.raw, y.call=y.raw,
      x.name=x.name, by.name=by.name, facet.name=facet.name, y.name=y.name,
      type=type, stat=stat, fill=fill, fill_palette=fill_palette,
      border=NULL, theme=theme, digits_d=digits_d,
      facet_gap_x=0.04, facet_gap_y=0.11, facet_size=1.00,
      facet_title_y_base =-0.018, facet_title_row_shift=-0.003,
      main=ttl,
      labels=labels, labels_position=labels_position,
      labels_color=labels_color, labels_size=labels_size
    )

    if (.allow.interactive() && !isTRUE(getOption("knitr.in.progress")))
      print(plt)

    return(invisible(plt))
  }


  else if (type == "pie") {  # plain pie, no by, maybe facet

    if (is.null(by.call) && !facet.miss) {  # by already shown to not exist
      by.name    <- facet.name
      by.call    <- facet.call    # use the facet as the by for aggregation
      facet.name <- NULL
      facet.call <- NULL
    }

    x.tbl <- .build_plotly_tbl(x.call, y.call, by.call, stat, is.agg)

    # build title unless user explicitly supplied main=
    ttl <- if (!main.miss && !is.null(main)) main[1]   # user supplied a title
           else if (main.miss) .plotly_build_title(
             x.name     = x.name,
             by.name    = if (!is.null(by.call)) by.name else NULL,
             facet.name = NULL,
             y.name     = if (!is.null(y.call)) y.name else NULL,
             stat       = if (!is.null(y.call)) stat   else NULL
           )
           else NULL

    plt <- piechart.plotly(
      x = x.tbl, x.name = x.name, y.name = y.name, by.name = by.name,
      main = ttl,
      fill = fill, border = color, opacity = 1 - trans,
      hole = hole, ncols = NULL,
      labels = labels, labels_position = labels_position,
      labels_color = labels_color, labels_size = labels_size,
      labels_decimals = labels_decimals,
      digits_d = digits_d
    )

    plt <- .finalize_plotly_widget(
      plt,
      kind         = "pie",
      x.name       = x.name,
      by.name      = if (!is.null(by.call)) by.name else NULL,
      add_title    = FALSE,
      nudge_viewer = (.allow.interactive() &&
                      !isTRUE(getOption("knitr.in.progress")))
    )

    if (.allow.interactive() && !isTRUE(getOption("knitr.in.progress")))
      print(plt)

    return(invisible(plt))
  }


# Bubble chart -----------------------------------------------------------

  else if (type == "bubble") {

    if (color.miss) color <- "black"
    # gray theme with no user fill: uniform gray30 so size alone encodes magnitude
    fill_bub <- if (fill.miss && identical(theme, "gray")) "gray30" else fill

    x.tbl <- .build_plotly_tbl(x.call, y.call, by.call, stat, is.agg)

    # build title unless user explicitly supplied main=
    ttl <- if (!main.miss && !is.null(main)) main[1]   # user supplied a title
           else if (main.miss) .plotly_build_title(     # user said nothing → auto
             x.name     = x.name,
             by.name    = if (!is.null(by.call)) by.name else NULL,
             facet.name = NULL,
             y.name     = if (!is.null(y.call)) y.name else NULL,
             stat       = if (!is.null(y.call)) stat   else NULL
           )
           else NULL

    plt <- bubble.plotly(
      x = x.tbl, x.name = x.name, y.name = y.name, by.name = by.name,
      x.lab = x.name, y.lab = if (is.null(by.call)) "" else by.name,
      main = ttl,
      fill = fill_bub, clr = color, opacity = 1 - trans,
      power = power, radius = radius,
      digits_d = digits_d,
      labels = labels, labels_position = labels_position,
      labels_size = labels_size, labels_color = labels_color
    )

    plt <- .finalize_plotly_widget(
      plt,
      kind         = "bubble",
      x.name       = x.name,
      by.name      = if (!is.null(by.call)) by.name else NULL,
      add_title    = FALSE,
      nudge_viewer = (.allow.interactive() &&
                      !isTRUE(getOption("knitr.in.progress")))
    )

    if (.allow.interactive() && !isTRUE(getOption("knitr.in.progress")))
      print(plt)

    return(invisible(plt))
  }


# Radar chart -------------------------------------------------------------

  else if (type == "radar") {

      n.x <- length(unique(x.call))
      if (n.x < 3) {  # Axes must define a polygon
        stop("\n\n",
          "radar(): The first categorical variable (x) must have at least ",
          "3 levels to form a polygon. ",
          "Found ", n.x, " levels for ", x.name, "."
        )
      }
      if (n.by == 1) {  # Must have at least two groups to compare
        stop("\n\n",
          "radar(): The second categorical variable (y) must have at least ",
          "2 levels to define multiple polygons. ",
          "Found ", n.by,  " levels for ", by.name, "."
        )
      }

      # stop when any cell is empty:
      # not working now because NA's cause by.call and x.call different lengths
      if (!is.null(by.call)) {

        # ensure x is a vector
        xv <- if (is.data.frame(x.call)) x.call[[1L]] else x.call
        ok <- complete.cases(by.call, xv)

        tbl <- table(by.call[ok], xv[ok], useNA = "no")

        if (any(tbl == 0L)) {
          zeros <- which(tbl == 0L, arr.ind = TRUE)
          print(tbl)

          stop("\n\n",
               "radar(): One or more cells are missing, with 0 entries.\n",
               "Radar polygons assume each group has a value at every axis.\n",
               "Here, ", nrow(zeros), "  cells were found with count=0.\n\n",
               "Use a larger sample, reduce the number of levels,\n",
               " or choose a different chart.\n")
        }
      }

      if (transparency.miss && !is.null(by.call))
        trans <- 0.4

      ttl <- if (!main.miss && !is.null(main)) main[1]
             else if (main.miss) .plotly_build_title(
               x.name     = x.name,
               by.name    = if (!is.null(by.call)) by.name else NULL,
               facet.name = if (!is.null(facet.call)) facet.name else NULL,
               y.name     = if (!is.null(y.call)) y.name else NULL,
               stat       = if (!is.null(y.call)) stat   else NULL
             )
             else NULL   # main=NULL explicitly supplied — no title

      plt <- .radar.plotly(
        x.call       = x.call,
        by.call      = by.call,
        facet.call   = facet.call,
        y.call       = y.call,
        x.name       = x.name,
        by.name      = by.name,
        facet.name   = facet.name,
        y.name       = y.name,
        main         = ttl,
        stat         = stat,
        fill         = fill,
        border       = color,
        opacity      = 1 - trans,
        digits_d     = digits_d,
        # facet layout controls (same names as hierarchical for consistency)
        facet_size  = 1.00,
        facet_gap_x = 0.04,
        facet_gap_y = 0.11,
        facet_title_y_base    = -0.018,  # down a bit into panel
        facet_title_row_shift = -0.003  # additional downshift per lower row
      )

    if (.allow.interactive() && !isTRUE(getOption("knitr.in.progress")))
      print(plt)

    return(invisible(plt))
    }


# Chart(x=, y=, ...,  type="dot") -> dot.plotly() directly ---------------

  else if (type == "dot") {

      # shared dot.plotly() parameters derived from Chart()'s resolved state
      dot_border  <- getOption("pt_color")
      dot_shape   <- 21
      dot_size    <- pt_size  # pt_size=.9 default → px = 6.5 pixels
      dot_opacity <- 1 - getOption("trans_pt_fill")
      # default fill from theme options, same as XY() scatter points
      if (fill.miss) fill <- .color_range(getOption("pt_fill"), max(n.x, n.by))

      # ---- paired dot plot: x=Person (cat), y=c(Before, After) (numeric df) -
      if (is.data.frame(y.call) && ncol(y.call) > 1L) {

        # ensure origin_x is numeric — NULL causes rep(NULL,n)=NULL mismatch
        if (is.null(origin_x)) origin_x <- 0

        cats_vec <- as.character(x.call)

        # apply sort= — order rows by row mean across all series
        if (sort != "0") {
          srt.dwn  <- sort == "-"
          row_means <- rowMeans(as.matrix(y.call), na.rm = TRUE)
          ord      <- order(row_means, decreasing = srt.dwn)
          cats_vec <- cats_vec[ord]
          y.call   <- y.call[ord, , drop = FALSE]
        }

        x.lab_dot <- if (!is.null(xlab)) xlab else ""
        gridT_dot <- pretty(c(origin_x, unlist(y.call)))

        plt <- dot.plotly(
          cats      = cats_vec,
          vals      = y.call,        # data frame → paired path in dot.plotly()
          fill      = fill[seq_len(min(ncol(y.call), length(fill)))],
          border    = dot_border,
          shape     = dot_shape,
          pt.size   = dot_size,
          x.lab     = x.lab_dot,
          y.lab     = x.name,
          digits_d  = if (!is.null(digits_d)) digits_d else 2,
          pt_opacity = dot_opacity,
          gridT     = gridT_dot,
          origin_x  = origin_x,
          height    = NULL,
          main      = if (!main.miss && !is.null(main)) main[1]
                      else if (main.miss) .plotly_build_title(
                        x.name     = x.name,
                        by.name    = NULL,
                        facet.name = NULL,
                        y.name     = y.name,
                        stat       = stat
                      ) else NULL,
          segments_x = if (!is.null(segments_x)) segments_x else TRUE,
          segments_y = if (!is.null(segments_y)) segments_y else TRUE
        )

        if (.allow.interactive() && !isTRUE(getOption("knitr.in.progress")))
          print(plt)
        return(invisible(plt))
      }

      # ---- single-series: aggregate if needed, then call dot.plotly() ------

      x_is_cat  <- is.factor(x.call) || is.character(x.call)
      has_dupes <- x_is_cat && length(x.call) > length(unique(x.call))
      needs_agg <- !is.agg && (has_dupes || (!is.null(stat) && !is.null(y.call)))

      # For faceted dot charts, pass raw data to dot.plotly() which aggregates
      # within each panel. Compute gridT from full data for consistent axes.
      if (!is.null(facet.call)) {
        x.lab_dot <- if (!is.null(ylab)) ylab
                     else if (!is.null(y.call)) y.name
                     else paste("Count of", x.name)
        orientation <- if (horiz) "h" else "v"
        x.lab_arg   <- if (horiz) x.lab_dot else x.name
        y.lab_arg   <- if (horiz) x.name     else x.lab_dot

        if (needs_agg && !is.null(y.call)) {
          stat_use <- if (!is.null(stat)) stat else "mean"
          stat_out <- .stats(x.call, y.call, NULL, NULL, stat_use, y.name)
          all_vals <- as.vector(stat_out$out)
          x.lab_dot <- if (!is.null(xlab)) xlab else stat_out$ylab
          x.lab_arg <- x.lab_dot
        } else if (!is.null(y.call)) {
          all_vals <- as.numeric(y.call)
        } else {
          all_vals <- as.integer(table(x.call))
        }

        fv <- all_vals[is.finite(all_vals)]
        origin_val      <- if (orientation == "h") origin_x else origin_y
        origin_val_miss <- is.null(origin_val)
        if (origin_val_miss) {
          if (is.null(y.call)) {
            # counts always start from 0
            origin_val <- 0
          } else {
            fv2  <- if (all(fv < 0)) -fv else fv
            mn.v <- min(fv2); mx.v <- max(fv2)
            if (mn.v > 0 && (mx.v - mn.v) / mn.v <= 2.40)
              origin_val <- mn.v
          }
        }
        gridT_dot <- pretty(c(if (!is.null(origin_val)) origin_val
                               else min(fv), fv))
        # nudge only for continuous y, not counts
        if (origin_val_miss && !is.null(y.call) && length(gridT_dot) > 1L) {
          step       <- gridT_dot[2L] - gridT_dot[1L]
          origin_val <- gridT_dot[1L] - step
          gridT_dot  <- pretty(c(origin_val, fv))
        }

        ttl_dot <- if (!main.miss && !is.null(main)) main[1]
                   else if (main.miss) .plotly_build_title(
                     x.name     = x.name,
                     by.name    = NULL,
                     facet.name = if (!is.null(facet.call)) facet.name else NULL,
                     y.name     = if (!is.null(y.call)) y.name else NULL,
                     stat       = if (!is.null(y.call)) stat   else NULL
                   )
                   else NULL

        plt <- dot.plotly(
          cats        = as.character(x.call),
          vals        = if (!is.null(y.call)) as.numeric(y.call)
                        else rep(1L, length(x.call)),
          orientation = orientation,
          fill        = fill[1],
          border      = dot_border,
          shape       = dot_shape,
          pt.size     = dot_size,
          x.lab       = x.lab_arg,
          y.lab       = y.lab_arg,
          digits_d    = if (!is.null(digits_d)) digits_d else 2,
          pt_opacity  = dot_opacity,
          gridT       = gridT_dot,
          origin_x    = origin_val,
          height      = NULL,
          facet       = facet.call,
          facet_name  = facet.name,
          stat        = if (!is.null(stat)) stat else if (is.null(y.call)) "sum" else NULL,
          sort        = sort,
          main        = ttl_dot,
          segments_x  = if (!is.null(segments_x)) segments_x else TRUE,
          segments_y  = if (!is.null(segments_y)) segments_y else TRUE
        )

        if (.allow.interactive() && !isTRUE(getOption("knitr.in.progress")))
          print(plt)
        return(invisible(plt))
      }

      if (needs_agg) {
        if (is.null(y.call)) {
          agg <- table(x.call)
          if (sort != "0") {
            agg <- sort(agg, decreasing = (sort == "-"))
          } else {
            agg <- agg[sort(names(agg))]  # alphabetical, consistent with bar chart
          }
          cats_vec  <- names(agg)
          vals_vec  <- as.integer(agg)
          x.lab_dot <- if (!is.null(xlab)) xlab else paste("Count of", x.name)
        } else {
          stat_use  <- if (!is.null(stat)) stat else "mean"
          stat_out  <- .stats(x.call, y.call, NULL, NULL, stat_use, y.name)
          out       <- stat_out$out
          cats_vec  <- names(out)
          vals_vec  <- as.vector(out)
          x.lab_dot <- if (!is.null(xlab)) xlab else stat_out$ylab
        }
      } else {
        # already aggregated / unique
        if (is.null(y.call)) {
          cat("\n"); stop(call.=FALSE, "\n------\n",
            "Need to specify a numerical variable for y, y=NAME\n\n")
        }
        if (x_is_cat) {
          # When stat aggregation was done upstream, x.call/y.call already hold
          # the reduced aggregated data. x.call.all/y.call.all only apply for
          # pre-aggregated input data where some categories may have NA values.
          if (!is.null(stat)) {
            cats_vec  <- as.character(x.call)
            vals_vec  <- as.numeric(y.call)
          } else {
            # pre-aggregated: use .all so all category labels appear on the axis;
            # dot.plotly() skips points where vals is NA (no dot, label stays).
            cats_vec  <- as.character(x.call.all)
            vals_vec  <- as.numeric(y.call.all)
          }
          x.lab_dot <- if (!is.null(ylab)) ylab else y.name
        } else {
          # x numeric, y categorical → horizontal
          cats_vec  <- as.character(y.call)
          vals_vec  <- as.numeric(x.call)
          x.lab_dot <- if (!is.null(xlab)) xlab else x.name
        }
      }

      # apply sort= to the category/value vectors
      if (sort != "0" && length(cats_vec) == length(vals_vec)) {
        srt.dwn <- sort == "-"
        ord <- order(vals_vec, decreasing = srt.dwn, na.last = TRUE)
        cats_vec <- cats_vec[ord]
        vals_vec <- vals_vec[ord]
      }

      # orientation: always horizontal (categories on y-axis) when x is
      # default: categories on x-axis (vertical bars), matching bar chart convention.
      # horiz=TRUE flips to horizontal (categories on y-axis).
      # Exception: x numeric + y categorical always stays vertical.
      if (!x_is_cat && !is.null(y.call)) {
        orientation <- "v"
        x.lab_arg   <- if (!is.null(xlab)) xlab else x.name
        y.lab_arg   <- x.lab_dot
      } else if (horiz) {
        orientation <- "h"
        x.lab_arg   <- if (!is.null(xlab)) xlab else x.lab_dot
        y.lab_arg   <- if (!is.null(ylab)) ylab else x.name
      } else {
        orientation <- "v"
        x.lab_arg   <- if (!is.null(xlab)) xlab else x.name
        y.lab_arg   <- if (!is.null(ylab)) ylab else x.lab_dot
      }

      # resolve value-axis origin: origin_x for horiz, origin_y for vertical
      origin_val <- if (orientation == "h") origin_x else origin_y

      # determine value-axis origin heuristic
      origin_val_miss <- is.null(origin_val)
      if (origin_val_miss) {
        if (is.null(y.call)) {
          # counts always start from 0
          origin_val <- 0
        } else {
          fv <- vals_vec[is.finite(vals_vec)]
          if (length(fv) > 0 && all(is.numeric(fv))) {
            fv2 <- if (all(fv < 0)) -fv else fv
            mn.v <- min(fv2, na.rm=TRUE)
            mx.v <- max(fv2, na.rm=TRUE)
            if (mn.v > 0) {
              prp <- (mx.v - mn.v) / mn.v
              if (prp <= 2.40) origin_val <- mn.v
            }
          }
        }
      }

      gridT_dot <- pretty(c(if (!is.null(origin_val)) origin_val
                            else min(vals_vec[is.finite(vals_vec)]),
                                     vals_vec[is.finite(vals_vec)]))

      # nudge one step below first tick only for continuous y, not counts
      if (origin_val_miss && !is.null(y.call) && length(gridT_dot) > 1L) {
        step       <- gridT_dot[2L] - gridT_dot[1L]
        origin_val <- gridT_dot[1L] - step
        gridT_dot  <- pretty(c(origin_val, vals_vec[is.finite(vals_vec)]))
      }

      plt <- dot.plotly(
        cats        = cats_vec,
        vals        = vals_vec,
        orientation = orientation,
        fill        = fill[1],
        border      = dot_border,
        shape       = dot_shape,
        pt.size     = dot_size,
        x.lab       = x.lab_arg,
        y.lab       = y.lab_arg,
        digits_d    = if (!is.null(digits_d)) digits_d else 2,
        pt_opacity  = dot_opacity,
        gridT       = gridT_dot,
        origin_x    = origin_val,
        height      = NULL,
        facet       = if (!is.null(facet.call)) facet.call else NULL,
        facet_name  = if (!is.null(facet.call)) facet.name else NULL,
        main        = if (!main.miss && !is.null(main)) main[1] else NULL,
        segments_x  = if (!is.null(segments_x)) segments_x else TRUE,
        segments_y  = if (!is.null(segments_y)) segments_y else TRUE
      )

      if (.allow.interactive() && !isTRUE(getOption("knitr.in.progress")))
        print(plt)
      return(invisible(plt))
    }

  }  # end x is a single var
  # ------------------------
  # ------------------------
  # x is a data frame or var list of multiple variables
  else {

    if (!by.miss || !facet.miss) {
      cat("\n"); stop(call.=FALSE, "\n------\n",
        "by and facet variables not available for multiple x variables\n\n")
    }

    # if labels not assigned, do default
    if (is.null(labels)) {
        labels <- getOption("labels")
        if (labels != "off") if (missing(y)) labels <- "input"
    }

    if (type == "bubble") {  # vector bubble, BPFM

      # get labels just for subset data matrix
      l <- attr(data, which="variable.labels")
      nm <- names(x.call)
      mylabs <- character(length=length(nm))
      for (i in seq_along(nm)) {
        if (!(nm[i] %in% names(l)))
          mylabs[i] <- "not available"
        else
          mylabs[i] <- l[which(names(l) == nm[i])]
      }
      if (all(mylabs == "not available")) mylabs <- NULL

      l.name <- "l"
      if (l.name %in% ls(name=.GlobalEnv))
        mylabs <- get(l.name, pos=.GlobalEnv)

      if (is.null(xlab)) xlab <- ""  # suppress x-axis label if not specified

    if (is.null(fill)) fill <- getOption("bar_fill_cont")
    if (transparency.miss) trans <- 0.4

    .dpmat.main(
      x=data[, , drop = FALSE], l=mylabs,
      sort_type=sort,

      fill=fill, color=getOption("pt_color"), col.bg=getOption("panel_fill"),
      trans=trans, shape_pts="bubble", col.box=getOption("panel_color"),
      col.low=NULL, col.hi=NULL,

      xy_ticks=TRUE,
      xlab=xlab, ylab=ylab, main=main, sub=sub, cex=1,

      radius=radius, power=power,
      size_cut=1,
      txt_color=getOption("bubble_text_color"),

      bm.adj=0, lm.adj=0, tm.adj=0, rm.adj=0,

      rotate_x=rotate_x, rotate_y=rotate_y, offset=offset, quiet=quiet,

      do_plot=do_plot, fun_call=fun_call,
      ...)
    }  # end vector bubble

    else if (type == "bar") {  # vector bar

    if (is.null(one_plot) || one_plot) {  # see if one_plot was specified
      one_plot <- TRUE

      mx.ln <- 0  # get variable with the most unique responses
      for (i in seq_len(ncol(data))) {
        ln <- length(na.omit(unique(data[,i])))
        if (ln > mx.ln) {
          ind <- i
          mx.ln <- ln
        }
      }
      uq <- na.omit(unique(data[,ind]))  # first largest set of responses
      uq.ln <- length(uq)  # length of largest set

      # all elements of smaller response set should be in full response set
      for (i in seq_len(ncol(data))) {
        if (length(setdiff(na.omit(unique(data[,i])), uq)) > 0) {
          one_plot <- FALSE
          break;
        }
      }
    }  # end determine one_plot

    # one_plot all x's stacked on a single plot, like a BPFM for bars
    if (one_plot) {
      y.call <- NULL
      by.call <- NULL
      if (is.null(legend_title)) legend_title <- "Responses"
      options(byname = "Responses")
      if (is.null(xlab)) xlab <- ""
      if (is.null(ylab)) ylab <- ""
      if (missing(labels_size)) labels_size <- 0.8 - (0.008 * ncol(data))
      if (sort.miss) sort <- "+"
      if (horiz.miss) horiz <- TRUE

      if (color.miss) color <- "transparent"

      # if fill not specified, define divergent palette and get colors
      if (fill.miss) {
        fill <- .get_fill(theme, diverge=TRUE)  # get divergent color names
        fill <-.color_range(fill, uq.ln)  # translate color names to colors
      }  # end fill.miss

      # evaluate getColors at the time of the function call
      # re-evaluate here by setting fill with the specified value of n
      else if (substr(fill.name, 1, 9) == "getColors")
        fill <- .do_getColors(fill.name, uq.ln)

      else  # not fill=getColors(...) but color names were specified
        fill <-.color_range(fill, uq.ln)  # translate color names to colors

      if (!is.null(pdf_file)) {
        if (!grepl(".pdf", pdf_file, fixed=TRUE))
          pdf_file <- paste(pdf_file, ".pdf", sep="")
        pdf(file=pdf_file, width=width, height=height, onefile=FALSE)
      }
      else {
        if (df.name != "NULL")  # not dev.new for shiny
            .opendev(pdf_file, width, height)
      }

      bc <- .bc.main(data, y.call, by.call, stack100,
            fill, color, trans,
            fill_split, fill_scaled, fill_chroma, fill_palette, theme,
            horiz, gap, proportion, scale_y,
            xlab, ylab, main,
            label_max, beside,
            rotate_x, offset,
            axis_fmt, axis_x_pre, axis_y_pre,
            break_x, sort,
            labels, labels_color, labels_size, labels_decimals,
            labels_position, labels_cut,
            xlab.adj, ylab.adj, bm.adj, lm.adj, tm.adj, rm.adj,
            pad_y_min, pad_y_max,
            legend_title, legend_position, legend_labels,
            legend_horiz, legend_size, legend_abbrev, legend_adjust,
            add, x1, x2, y1, y2, 80, do_plot, use_plotly=FALSE,
            quiet, shiny, digits_d, ...)

      if (!is.null(pdf_file)) {
        dev.off()
        if (!quiet) .showfile(pdf_file, "BarChart")
      }
    }  # end one_plot


    # --------------------------------
    # analyze each x column separately

    else {
      bc.data.frame(data, stack100,
        fill, color, trans, fill_split,
        fill_scaled, fill_chroma, theme,
        horiz, gap, proportion, scale_y,
        xlab, ylab, main,
        label_max, beside,
        rotate_x, offset, 
        axis_fmt, axis_x_pre, axis_y_pre,
        break_x, sort,
        labels, labels_color, labels_size, labels_decimals,
        labels_position, labels_cut,
        xlab.adj, ylab.adj, bm.adj, lm.adj, tm.adj, rm.adj,
        pad_y_min, pad_y_max,
        legend_title, legend_position, legend_labels,
        legend_horiz, legend_size, legend_abbrev, legend_adjust,
        80, do_plot, use_plotly=FALSE, quiet,
        digits_d, shiny, pdf_file, width, height, ...)
    }
  }
  } # end

}
