---
title: "ggplot2 and Thematic Integration with Brand Themes"
format:
  html:
    # Keep the installed vignettes small (the pkgdown site applies the full theme)
    minimal: true
brand: false
vignette: >
  %\VignetteIndexEntry{ggplot2 and Thematic Integration with Brand Themes}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  # Size figures close to the width of the page so text is not scaled down
  fig.width = 7,
  fig.height = 4.5,
  dpi = 150,
  out.width = "100%",
  # Render Google Fonts loaded by brand_set_ggplot() at the figure's dpi
  fig.showtext = TRUE
)
```

## Overview

This vignette demonstrates how to integrate ggplot2 and plotly visualizations with brand themes using the `rbranding` package. The package provides functions to:

1. Load brand configuration from `_brand.yml` files
2. Apply brand colors and typography to ggplot2 themes
3. Add brand logos to plots
4. Reset themes when needed

The examples use the [ForeSITE](https://github.com/EpiForeSITE) brand, which ships with the package.

## Getting Started

First, let's load the required packages:

```{r setup}
library(rbranding)
library(ggplot2)

# Suggested packages for enhanced functionality
# library(plotly)  # For interactive plots
# library(sysfonts)  # For custom fonts
# library(showtext)  # For custom fonts
```

## Step 1: Initialize and Load Brand Configuration

In a real project, you initialize the branding configuration once and then download the latest brand file:

```{r, eval = FALSE}
# Initialize branding (creates rbranding_config.yml and placeholder _brand.yml)
brand_init()

# Get the latest brand file from the repository
get_brand_public()

# Optionally, install the ggplot2 example template in your working directory
get_template("ggplot2")
```

For this vignette, we use the ForeSITE `_brand.yml` and logos bundled with the package, copied into a temporary directory:

```{r}
## Use a temporary directory as the knit root for the entire document so that
## subsequent chunks are evaluated with `temp_dir` as their working directory.
temp_dir <- file.path(tempdir(), "rbranding-ggplot2")
dir.create(temp_dir, showWarnings = FALSE)
knitr::opts_knit$set(root.dir = temp_dir)

brand_dir <- system.file("brand_files", package = "rbranding")
invisible(file.copy(
  list.files(brand_dir, full.names = TRUE),
  temp_dir,
  recursive = TRUE,
  overwrite = TRUE
))
brand_file <- file.path(temp_dir, "_brand.yml")
```

The brand defines three official colors, which we will also use for the data:

```{r}
brand <- yaml::read_yaml(brand_file)
foresite <- unlist(brand$color$palette[c("crimson", "gold", "dark-gray")])
foresite
```

## Step 2: Set the ggplot2 Theme

Apply the brand theme to ggplot2. This will set colors and fonts according to your brand configuration:

```{r}
brand_set_ggplot(brand_file)
```

The brand theme is a regular ggplot2 theme, so you can fine-tune it with `theme_update()`. Here we increase the text size for readability, use a light grid so the data stand out, and highlight titles in ForeSITE crimson:

```{r}
theme_update(
  text = element_text(size = 13),
  plot.title = element_text(size = 17, face = "bold", colour = foresite[["crimson"]]),
  plot.subtitle = element_text(size = 12, colour = foresite[["dark-gray"]]),
  plot.title.position = "plot",
  axis.text = element_text(size = 11),
  panel.grid.major = element_line(colour = "#E6E6E6", linewidth = 0.4),
  panel.grid.minor = element_blank(),
  legend.position = "bottom"
)
```

## Step 3: Create ggplot2 Visualizations

Now create some plots that will automatically use your brand theme. We map groups to the brand colors with `scale_*_manual()`. Gold has low contrast on white (1.7:1), so points and bars get a thin dark gray outline to keep them distinguishable:

```{r basic-plot, fig.alt="Scatterplot of car weight versus miles per gallon with points colored crimson, gold, and dark gray by number of cylinders, styled with the ForeSITE brand."}
p1 <- ggplot(mtcars, aes(x = mpg, y = wt, fill = factor(cyl))) +
  geom_point(shape = 21, size = 3.5, stroke = 0.4, colour = foresite[["dark-gray"]]) +
  scale_fill_manual(values = unname(foresite)) +
  labs(
    title = "Car Weight vs. Miles per Gallon",
    subtitle = "Data from the 1974 Motor Trend magazine",
    x = "Miles per Gallon",
    y = "Weight (1000 lbs)",
    fill = "Cylinders"
  )

print(p1)
```

```{r bar-plot, fig.alt="Grouped bar chart of car counts by number of cylinders and gears in crimson, gold, and dark gray, styled with the ForeSITE brand."}
p2 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(gear))) +
  geom_bar(position = position_dodge(width = 0.8), width = 0.75,
           colour = foresite[["dark-gray"]], linewidth = 0.3) +
  scale_fill_manual(values = unname(foresite)) +
  scale_y_continuous(breaks = seq(0, 12, by = 2), expand = expansion(mult = c(0, 0.05))) +
  labs(
    title = "Car Count by Cylinders and Gears",
    x = "Number of Cylinders",
    y = "Count",
    fill = "Gears"
  ) +
  theme(panel.grid.major.x = element_blank())

print(p2)
```

## Step 4: Add Brand Logo (Optional)

If your brand configuration includes a logo, you can add it to your plots. `size` is the logo's height as a fraction of the plot:

```{r logo-plot, eval = requireNamespace("png", quietly = TRUE), fig.alt="The car weight scatterplot with the ForeSITE logo in the top-right corner."}
p1_with_logo <- p1 + brand_add_logo(x = 0.94, y = 0.88, size = 0.16)
print(p1_with_logo)
```

## Step 5: Interactive Plots with plotly

You can also create interactive versions of your plots using plotly:

```{r plotly-example, eval=FALSE}
library(plotly)

# Convert ggplot to interactive plotly chart
p1_interactive <- ggplotly(p1, tooltip = c("x", "y", "fill"))
p1_interactive
```

## Step 6: Advanced Theming

You can customize specific aspects of the theme while maintaining brand consistency:

```{r advanced-theme, fig.alt="Bubble chart of miles per gallon versus horsepower with crimson bubbles sized by car weight, styled with the ForeSITE brand."}
p3 <- ggplot(mtcars, aes(x = hp, y = mpg, size = wt)) +
  geom_point(colour = foresite[["crimson"]], alpha = 0.6) +
  scale_size_continuous(range = c(2, 9)) +
  labs(
    title = "Engine Performance Analysis",
    subtitle = "Relationship between horsepower, fuel efficiency, and weight",
    x = "Horsepower",
    y = "Miles per Gallon",
    size = "Weight (1000 lbs)"
  ) +
  theme(
    plot.subtitle = element_text(face = "italic"),
    legend.position = "right"
  )

print(p3)
```

## Step 7: Reset Theme

When you're done with the brand theme, you can reset to the default ggplot2 theme:

```{r reset-theme, fig.alt="Scatterplot of car weight versus miles per gallon with the default ggplot2 theme and colors."}
# Reset to original theme
brand_reset_ggplot()

# Create a plot with default theme to show the difference
p4 <- ggplot(mtcars, aes(x = mpg, y = wt)) +
  geom_point(aes(color = factor(cyl)), size = 3) +
  labs(
    title = "Same Plot with Default Theme",
    x = "Miles per Gallon",
    y = "Weight (1000 lbs)",
    color = "Cylinders"
  )

print(p4)
```

## Best Practices

1. **Set theme early**: Call `brand_set_ggplot()` at the beginning of your analysis
2. **Test font loading**: Custom fonts may not work in all environments
3. **Use consistent colors**: Stick to the brand palette for consistency, and check contrast (e.g., outline light colors such as gold)
4. **Size figures for their destination**: Match `fig.width` to the width at which the figure is displayed so text is not scaled down
5. **Reset when needed**: Use `brand_reset_ggplot()` to return to default themes
6. **Logo placement**: Position logos where they don't interfere with data

## Troubleshooting

### Common Issues

- **Font loading fails**: Some environments may not support custom Google Fonts
- **Text looks too small**: The figure is wider than where it is displayed, or `showtext` renders at a different resolution than the figure; set `fig.showtext = TRUE` in knitr/Quarto documents
- **Logo not found**: Ensure the logo path in `_brand.yml` is correct and the file exists
- **Colors not applied**: Check that your `_brand.yml` file follows the correct schema

### Solutions

```{r troubleshooting, eval=FALSE}
# Disable custom fonts if having issues
brand_set_ggplot(use_fonts = FALSE)

# Check brand configuration
doc <- yaml::read_yaml("_brand.yml")
str(doc$color)
str(doc$typography)
```

## Conclusion

The `rbranding` package makes it easy to create consistent, branded visualizations across your organization. By following this workflow, you can ensure that all your ggplot2 and plotly charts maintain brand consistency while being accessible and professional.

For more information about the brand.yml schema, visit: https://github.com/posit-dev/brand-yml/
