Learn R Programming

pubrplot (version 0.0.1)

plot_bar: Bar Plot for Categorical Data with Optional Grouping

Description

Creates a publication-quality bar plot for a categorical variable, with optional grouping by another variable. Automatically calculates counts and percentages and can display them on the bars. Also performs Chi-square or Fisher exact test if by is provided.

Usage

plot_bar(
  data,
  var,
  by = NULL,
  vjust = -0.3,
  hjust = 0.5,
  axis.label.angle = 45,
  label = NULL,
  border.color = NULL,
  label.color = "black",
  x.lab = "Group",
  y.lab = "Percentage (%)",
  fill.lab = "Variable",
  text.size = 3,
  color.bar = NULL,
  theme_fun = ggthemes::theme_stata,
  bar.width = 0.8,
  y.expand = 1.12
)

Value

A ggplot2 object representing the bar plot.

Arguments

data

A data frame containing the variables to plot.

var

The main categorical variable to display on the x-axis (unquoted or quoted).

by

Optional grouping variable for stacked/dodged bars (unquoted or quoted). Default is NULL.

vjust

Vertical adjustment for text labels. Default is -0.3.

hjust

Horizontal adjustment for text labels. Default is 0.5.

axis.label.angle

Angle of x-axis labels. Default is 45.

label

Optional custom labels for factor levels of var.

border.color

Optional color for bar borders. Default is NULL.

label.color

Color of the text labels on bars. Default is "black".

x.lab

Label for x-axis. Default is "Group".

y.lab

Label for y-axis. Default is "Percentage (%)".

fill.lab

Legend title for the fill variable. Default is "Variable".

text.size

Size of the text labels. Default is 3.

color.bar

Optional vector of colors for bars.

theme_fun

Theme function from ggthemes (or ggplot2) for styling. Default is ggthemes::theme_stata.

bar.width

Width of the bars. Default is 0.8.

y.expand

Factor to expand the y-axis for space above the highest bar. Default is 1.12.

Examples

Run this code
# Example using CO2 dataset
plot_bar(
  CO2,
  var = "Type",
  by = "Treatment",
  fill.lab = "Plant Type",
  color.bar = c("lightblue","lightgreen"),
  border.color = "black",
  bar.width = 0.5,
  text.size = 3,
  label = c("Quebec","Mississippi")
)

# Example using diamonds dataset
plot_bar(
  ggplot2::diamonds,
  var = "cut",
  by = "color",
  y.lab = "Distribution (%)",
  fill.lab = "Cut",
  text.size = 2,
  bar.width = 0.9,
  color.bar = c("#a465db","steelblue","darkgreen","darkred","#fcba03")
)

# Simple bar plot without grouping
plot_bar(ggplot2::diamonds, var = "cut")

Run the code above in your browser using DataLab