Creating Bar Charts with viz_bar()
bar_vignette.Rmdπ Introduction
The viz_bar() function creates grouped/clustered bar
charts, perfect for comparing categories across different groups or
segments. Unlike histograms (which show distributions) or stacked bars
(which show composition), bar charts excel at side-by-side
comparisons.
π Basic Bar Charts
Simple Category Counts
# Sample data
data <- data.frame(
category = c("A", "A", "B", "B", "B", "C", "C", "C", "C")
)
# Create bar chart
plot <- viz_bar(
data = data,
x_var = "category"
)
plotWith Custom Labels
plot <- viz_bar(
data = data,
x_var = "category",
title = "Category Distribution",
x_label = "Categories",
y_label = "Count"
)
plotπ Grouped Bar Charts
Basic Grouping
# Survey data
survey_data <- data.frame(
question = rep(c("Q1", "Q2", "Q3"), each = 50),
score_range = sample(c("Low", "Medium", "High"), 150, replace = TRUE)
)
# Grouped bar chart
plot <- viz_bar(
data = survey_data,
x_var = "question",
group_var = "score_range",
horizontal = TRUE,
bar_type = "percent"
)
plotWith Custom Colors
plot <- viz_bar(
data = survey_data,
x_var = "question",
group_var = "score_range",
horizontal = TRUE,
bar_type = "percent",
title = "Survey Scores by Question",
x_label = "Question",
y_label = "Percentage",
color_palette = c(
"#E74C3C", # Red for Low
"#F39C12", # Orange for Medium
"#27AE60" # Green for High
),
group_order = c("Low", "Medium", "High")
)
plotβοΈοΈ Horizontal vs.Β Vertical
Vertical Bars
plot <- viz_bar(
data = survey_data,
x_var = "question",
group_var = "score_range",
horizontal = FALSE, # Vertical (default)
title = "Score Distribution",
x_label = "Question",
y_label = "Count"
)
plotHorizontal Bars (Better for Long Labels)
data <- data.frame(
question = rep(c(
"I know how to search effectively",
"I can evaluate information quality",
"I understand data privacy"
), each = 40),
response = sample(c("Agree", "Disagree"), 120, replace = TRUE)
)
plot <- viz_bar(
data = data,
x_var = "question",
group_var = "response",
horizontal = TRUE, # Much better for long labels!
bar_type = "percent",
title = "Digital Literacy Self-Assessment",
y_label = "Percentage",
color_palette = c("#2ECC71", "#E74C3C") # Green for Agree, Red for Disagree
)
plotπ’ Count vs.Β Percent
Count
plot <- viz_bar(
data = survey_data,
x_var = "question",
group_var = "score_range",
bar_type = "count", # Show raw counts
title = "Response Counts by Question",
x_label = "Survey Question",
y_label = "Number of Responses"
)
plotPercent
plot <- viz_bar(
data = survey_data,
x_var = "question",
group_var = "score_range",
bar_type = "percent", # Show percentages
title = "Response Distribution",
x_label = "Survey Question",
y_label = "Percentage"
)
plotπ Means with Error Bars
When analyzing numeric outcomes across categories, use
bar_type = "mean" with error bars to show statistical
uncertainty.
Basic Mean Chart with Error Bars
# Create sample data with a continuous outcome
performance_data <- data.frame(
group = rep(c("Control", "Treatment A", "Treatment B"), each = 50),
score = c(
rnorm(50, mean = 70, sd = 10), # Control
rnorm(50, mean = 75, sd = 12), # Treatment A
rnorm(50, mean = 80, sd = 8) # Treatment B
)
)
# Mean with 95% confidence intervals
plot <- viz_bar(
data = performance_data,
x_var = "group",
value_var = "score",
bar_type = "mean",
error_bars = "ci",
title = "Performance by Treatment Group",
x_label = "Group",
y_label = "Mean Score",
color_palette = c("#3498DB", "#E74C3C", "#27AE60")
)
plotError Bar Types
| Type | Parameter | Shows |
|---|---|---|
| Standard Deviation | error_bars = "sd" |
Spread of individual values |
| Standard Error | error_bars = "se" |
Precision of the mean estimate |
| Confidence Interval | error_bars = "ci" |
Range likely to contain true mean |
# Standard error bars (smaller, shows precision)
plot_se <- viz_bar(
data = performance_data,
x_var = "group",
value_var = "score",
bar_type = "mean",
error_bars = "se",
title = "Mean Β± Standard Error",
y_label = "Mean Score"
)
plot_seGrouped Means with Error Bars
# Add a grouping variable
grouped_data <- data.frame(
treatment = rep(c("Placebo", "Drug A", "Drug B"), each = 100),
gender = rep(c("Male", "Female"), 150),
outcome = rnorm(300, mean = 50, sd = 15)
)
# Adjust means by group
grouped_data$outcome <- grouped_data$outcome +
ifelse(grouped_data$treatment == "Drug A", 5, 0) +
ifelse(grouped_data$treatment == "Drug B", 10, 0) +
ifelse(grouped_data$gender == "Female", 3, 0)
plot <- viz_bar(
data = grouped_data,
x_var = "treatment",
group_var = "gender",
value_var = "outcome",
bar_type = "mean",
error_bars = "ci",
ci_level = 0.95,
title = "Treatment Effect by Gender",
x_label = "Treatment",
y_label = "Mean Outcome (95% CI)",
color_palette = c("#3498DB", "#E74C3C")
)
plotCustomizing Error Bar Appearance
plot <- viz_bar(
data = performance_data,
x_var = "group",
value_var = "score",
bar_type = "mean",
error_bars = "ci",
error_bar_color = "#2C3E50", # Dark color for visibility
error_bar_width = 30, # Narrower whiskers (0-100)
title = "Custom Error Bar Styling",
y_label = "Mean Score"
)
plotπ·οΈ Labels and Tooltips
Tooltip Customization
Add prefix/suffix text to make tooltips more informative:
plot <- viz_bar(
data = survey_data,
x_var = "question",
group_var = "score_range",
bar_type = "percent",
title = "Score Distribution",
x_label = "Question",
y_label = "Percentage",
tooltip_prefix = "",
tooltip_suffix = "% of responses",
x_tooltip_suffix = ""
)
plotFor more control, use format strings or the tooltip()
helper:
# Format string with placeholders
viz_bar(data, x_var = "category",
tooltip = "{category}: {value} ({percent})")
# Full control with tooltip() helper
viz_bar(data, x_var = "category",
tooltip = tooltip(
format = "<b>{category}</b>: {value}",
backgroundColor = "#f8f9fa",
borderRadius = 8
))| Parameter | Description | Example |
|---|---|---|
x_label |
X-axis title | "Category" |
y_label |
Y-axis title |
"Count", "Percentage"
|
tooltip |
Full tooltip config (see ?tooltip) |
tooltip(format = "...") |
tooltip_prefix |
Text before value in tooltip | "N = " |
tooltip_suffix |
Text after value in tooltip |
"%", " respondents"
|
x_tooltip_suffix |
Text after x value in tooltip | " category" |
See vignette("getting-started") for the complete tooltip
customization guide.
π’ Working with Numeric Variables
Automatic Binning
# Age data
age_data <- data.frame(
age = sample(18:65, 200, replace = TRUE)
)
# Automatically bins numeric values
plot <- viz_bar(
data = age_data,
x_var = "age",
title = "Age Distribution",
x_label = "Age",
y_label = "Count",
color_palette = c("#3498DB")
)
plotπ¨ Advanced Styling
Custom Ordering
data <- data.frame(
satisfaction = sample(c("Very Satisfied", "Satisfied", "Neutral",
"Dissatisfied", "Very Dissatisfied"),
100, replace = TRUE)
)
plot <- viz_bar(
data = data,
x_var = "satisfaction",
x_order = c("Very Dissatisfied", "Dissatisfied", "Neutral",
"Satisfied", "Very Satisfied"),
title = "Customer Satisfaction",
x_label = "Satisfaction Level",
y_label = "Number of Responses",
color_palette = c("#C0392B", "#E74C3C", "#95A5A6", "#27AE60", "#1E8449")
)
plotColorful Individual Bars
# When no group_var, can color each bar differently
data <- data.frame(
category = c("A", "B", "C", "D")
)
plot <- viz_bar(
data = data,
x_var = "category",
title = "Category Overview",
x_label = "Category",
y_label = "Count",
color_palette = c("#3498DB", "#E74C3C", "#F39C12", "#27AE60"),
tooltip_suffix = " items"
)
plotπ Real-World Examples
Survey Response Comparison
# Knowledge assessment across topics
knowledge_data <- data.frame(
topic = rep(c("Search Skills", "Critical Thinking",
"Data Privacy", "Source Evaluation"), each = 100),
proficiency = sample(c("Beginner", "Intermediate", "Advanced"),
400, replace = TRUE)
)
plot <- viz_bar(
data = knowledge_data,
x_var = "topic",
group_var = "proficiency",
horizontal = TRUE,
bar_type = "percent",
title = "Self-Reported Proficiency by Topic",
x_label = "",
y_label = "Percentage of Respondents",
color_palette = c("#E74C3C", "#F39C12", "#27AE60"),
group_order = c("Beginner", "Intermediate", "Advanced")
)
plotDemographic Breakdown
demo_data <- data.frame(
age_group = rep(c("18-24", "25-34", "35-44", "45-54", "55+"), each = 80),
device_type = sample(c("Mobile", "Desktop", "Tablet"), 400, replace = TRUE)
)
plot <- viz_bar(
data = demo_data,
x_var = "age_group",
group_var = "device_type",
horizontal = FALSE,
bar_type = "percent",
title = "Device Usage by Age Group",
x_label = "Age Group",
y_label = "Percentage",
color_palette = c("#3498DB", "#95A5A6", "#F39C12"),
tooltip_suffix = "%"
)
plotπ Using with create_viz()
Integrate with the dashboard workflow:
viz <- create_viz(
type = "bar",
horizontal = TRUE,
bar_type = "percent",
color_palette = c("#E74C3C", "#F39C12", "#27AE60")
) %>%
add_viz(
x_var = "question1",
group_var = "response_category",
title = "Question 1 Results"
) %>%
add_viz(
x_var = "question2",
group_var = "response_category",
title = "Question 2 Results"
) %>%
add_viz(
x_var = "question3",
group_var = "response_category",
title = "Question 3 Results"
)
# All inherit the defaults!With Tabgroups
viz <- create_viz(
type = "bar",
horizontal = TRUE,
bar_type = "percent"
) %>%
add_viz(
x_var = "satisfaction",
group_var = "score_range",
title = "By Age",
tabgroup = "demographics/age"
) %>%
add_viz(
x_var = "satisfaction",
group_var = "score_range",
title = "By Gender",
tabgroup = "demographics/gender"
) %>%
add_viz(
x_var = "satisfaction",
group_var = "score_range",
title = "By Education",
tabgroup = "demographics/education"
)π Comparison with Other Chart Types
When to Use Bar Charts
Use viz_bar() when: - Comparing
categories across groups - Showing side-by-side comparisons - Displaying
survey responses by demographics - You want grouped/clustered bars -
Showing means with error bars (SD, SE, or CI)
Use viz_stackedbar() when: - Showing
composition (parts of a whole) - Displaying Likert scale responses -
Emphasizing proportions within categories
Use viz_histogram() when: - Showing
distributions of continuous variables - Displaying frequency
distributions - Analyzing data spread and shape
Use viz_timeline() when: - Showing
changes over time - Displaying trends - Comparing time series
π‘ Tips and Best Practices
- Use horizontal bars for long labels - Much more readable
- Choose percent for comparisons - Easier to interpret than counts
-
Order categories meaningfully - Use
x_orderorgroup_order - Limit colors - 3-5 colors maximum for clarity
- Use consistent colors - Same meaning = same color across charts
π See Also
-
?viz_bar- Full function documentation -
vignette("stackedbar_vignette")- For stacked/composed bars -
vignette("advanced-features")- For defaults and filters -
vignette("getting-started")- For dashboard integration