---
title: "Creating Bar Charts with viz_bar()"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Creating Bar Charts with viz_bar()}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  warning = FALSE,
  message = FALSE
)
```

## 📖 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.

```{r setup}
library(dashboardr)
library(dplyr)
```

## 📊 Basic Bar Charts

### Simple Category Counts

```{r}
# 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"
)

plot
```

### With Custom Labels

```{r}
plot <- viz_bar(
  data = data,
  x_var = "category",
  title = "Category Distribution",
  x_label = "Categories",
  y_label = "Count"
)

plot
```

## 📊 Grouped Bar Charts

### Basic Grouping

```{r}
# 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"
)

plot
```

### With Custom Colors

```{r}
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

```{r}
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"
)

plot
```

### Horizontal Bars (Better for Long Labels)

```{r}
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

```{r}
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"
)

plot
```

### Percent

```{r}
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

```{r}
# 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")
)

plot
```

### Error 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 |

```{r}
# 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_se
```

### Grouped Means with Error Bars

```{r}
# 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")
)

plot
```

### Customizing Error Bar Appearance

```{r}
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

### Axis Labels

```{r}
plot <- viz_bar(
  data = survey_data,
  x_var = "question",
  group_var = "score_range",
  title = "Survey Results",
  x_label = "Question",
  y_label = "Percentage of Respondents",
  bar_type = "percent",
  color_palette = c("#9B59B6", "#3498DB", "#1ABC9C")  # Purple, Blue, Teal
)

plot
```

### Tooltip Customization

Add prefix/suffix text to make tooltips more informative:

```{r}
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 = ""
)

plot
```

For more control, use format strings or the `tooltip()` helper:

```{r, eval=FALSE}
# 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

```{r}
# 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
```

### Custom Binning

```{r}
plot <- viz_bar(
  data = age_data,
  x_var = "age",
  x_breaks = c(18, 25, 35, 50, 65),
  x_bin_labels = c("18-24", "25-34", "35-49", "50-64"),
  title = "Age Groups",
  x_label = "Age Range",
  y_label = "Number of Respondents",
  tooltip_suffix = " people"
)

plot
```

## 🎨 Advanced Styling

### Custom Ordering

```{r}
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")
)

plot
```

### Colorful Individual Bars

```{r}
# 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

```{r}
# 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")
)

plot
```

### Demographic Breakdown

```{r}
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:

```{r}
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 Filters

```{r}
viz <- create_viz(
  type = "bar",
  x_var = "satisfaction",
  group_var = "score_range",
  horizontal = TRUE,
  bar_type = "percent"
) %>%
  add_viz(title = "Wave 1", filter = ~ wave == 1) %>%
  add_viz(title = "Wave 2", filter = ~ wave == 2) %>%
  add_viz(title = "Wave 3", filter = ~ wave == 3)
```

### With Tabgroups

```{r}
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

1. **Use horizontal bars for long labels** - Much more readable
2. **Choose percent for comparisons** - Easier to interpret than counts
3. **Order categories meaningfully** - Use `x_order` or `group_order`
4. **Limit colors** - 3-5 colors maximum for clarity
5. **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

