Skip to contents

This function creates a customized bar plot using ggplot2 with Insper's visual identity. Supports grouped bars, text labels, and automatic orientation.

Usage

insper_barplot(
  data,
  x,
  y,
  fill = NULL,
  position = "dodge",
  palette = "categorical",
  zero = TRUE,
  text = FALSE,
  text_size = 4,
  text_color = "black",
  stack_vjust = 0.5,
  label_formatter = scales::comma,
  ...
)

Arguments

data

A data frame containing the data to plot

x

Column name for x-axis

y

Column name for y-axis

fill

Fill aesthetic. Accepts either:

  • A bare column name for variable mapping (e.g., fill = gear)

  • A quoted color string for static fill (e.g., fill = "blue")

  • NULL (default) to use default Insper red

When mapping a variable, creates grouped or stacked bars based on position.

position

Position adjustment for bars. Options: "dodge", "stack", "fill", "identity". Default is "dodge"

palette

Character. Color palette for variable mappings. Default is "categorical".

zero

Logical. If TRUE, adds a horizontal line at y = 0. Default is TRUE

text

Logical. If TRUE, adds value labels on bars. Default is FALSE

text_size

Numeric. Size of text labels. Default is 4

text_color

Character. Color of text labels. Default is "black". For position = "fill", automatic contrast-based colors are used if not specified.

stack_vjust

Numeric. Vertical adjustment for text labels in stacked/filled bars. Range: 0 (bottom) to 1 (top). Default is 0.5 (center). Only applies when position = "stack" or "fill"

label_formatter

Function. Formatter for text labels. Default is scales::comma. For position = "fill", percentages are automatically formatted if values are proportions

...

Additional arguments passed to ggplot2::geom_col(), allowing custom aesthetics like width, alpha, etc.

Value

A ggplot2 object

Details

The function automatically detects bar orientation based on variable types:

  • **Vertical bars**: When x is categorical and y is numeric (default)

  • **Horizontal bars**: When x is numeric and y is categorical

Text labels and zero lines automatically adjust to the detected orientation.

Examples

if (FALSE) { # has_insper_fonts()
# Simple bar plot with default color
insper_barplot(mtcars, x = factor(cyl), y = mpg)

# With text labels showing values
insper_barplot(mtcars, x = factor(cyl), y = mpg, text = TRUE)

# Stacked bars with centered text labels
data <- data.frame(
  category = rep(c("A", "B", "C"), each = 2),
  group = rep(c("X", "Y"), 3),
  value = c(10, 15, 20, 25, 30, 35)
)
insper_barplot(data, x = category, y = value, fill = group,
               position = "stack", text = TRUE)

# Filled bars with automatic percentage formatting
insper_barplot(data, x = category, y = value, fill = group,
               position = "fill", text = TRUE)
}