Skip to contents

Create a simple bar plot

Usage

plot_bar(
  data,
  formula,
  type = c("percent", "count"),
  fill = "#0032A0",
  layout = c("sbs", "stack"),
  orient = c("vertical", "horizontal"),
  dodge = 1,
  title = NULL,
  subtitle = c("show", "hide"),
  na_rm = TRUE,
  ...
)

Arguments

data

A data frame.

formula

The variable to tabulate. Should be given in formula notation, ~var.

type

The type of plot to create. Valid options are "percent" (the default) or "count".

fill

The fill of the plot. Valid options are a character color (for one variable plots) or a variable given in formula notation (~var), used to create a grouped bar plot.

layout

The bar type for grouped plots. Either "sbs" for side-by-side bars or "stack" for stacked bars. fill must be a variable for this to go into effect.

orient

The orientation for the plot (either "vertical", the default, or "horizontal"). As a shortcut, "v" and "h" may be used.

dodge

The number of rows to dodge the axis labels to, should they be overlapping.

title

An override for the title of the plot. A sensible default is provided.

subtitle

A switch for hiding the default subtitle. One of "show" or "hide".

na_rm

Should missing values be removed? Defaults to TRUE.

...

Extra title arguments passed on to ggformula::gf_labs() (which feeds to ggplot2::ggplot()).

Value

A ggplot object. In an interactive session, results are viewable immediately.

Examples

plot_bar(mtcars, ~cyl)
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.

plot_bar(mtcars, ~cyl, type = "count")

plot_bar(mtcars, ~cyl, type = "percent", fill = "yellowgreen")
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.

plot_bar(mtcars, ~cyl, orient = "horizontal")
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.

plot_bar(dplyr::starwars, ~hair_color, dodge = 2)
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.

plot_bar(mtcars, ~cyl, subtitle = "hide")
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.


plot_bar(mtcars, ~cyl, fill = ~gear)

plot_bar(mtcars, ~cyl, fill = ~gear, layout = "stack")

plot_bar(mtcars, ~cyl, type = "count", fill = ~gear)