---
title: Transforms
---

```{r}
library(gglite)
```

Transforms are data manipulations applied to marks, similar to ggplot2's
`stat_*()` and `position_*()` functions. Use `transform()` to add them.

## stackY (position_stack)

Stack bars vertically.

```{r}
df = data.frame(
  x = rep(c('A', 'B', 'C'), each = 2), y = c(3, 2, 5, 4, 1, 6),
  color = rep(c('a', 'b'), 3)
)
p = g2(df, y ~ x, color = ~ color) |> mark_interval()
p |> transform('stackY')
```

### Stacked area chart

```{r}
df = data.frame(
  x = rep(1:5, 2), y = c(3, 1, 4, 1, 5, 2, 7, 1, 8, 3),
  group = rep(c('A', 'B'), each = 5)
)
g2(df, y ~ x, color = ~ group) |>
  mark_area() |>
  transform('stackY')
```

## dodgeX (position_dodge)

Place bars side by side.

```{r}
p |> transform('dodgeX')
```

## normalizeY (position_fill)

Normalize to 100% (percent-stacked chart).

```{r}
p |>
  transform('stackY') |>
  transform('normalizeY')
```

## jitterX / jitterY

Add random jitter to reduce overplotting.

```{r}
g2(mtcars, hp ~ cyl) |>
  transform('jitterX')
```

### Jitter in both directions

```{r}
g2(mtcars, gear ~ cyl) |>
  transform('jitterX') |>
  transform('jitterY')
```

## binX (stat_bin)

Bin data along x for histograms.

```{r}
g2(mtcars, ~ mpg) |>
  mark_rect() |>
  transform('binX', y = 'count', thresholds = 15)
```

## bin (2D binning)

Bin in two dimensions for heatmap-style plots.

```{r}
g2(mtcars, hp ~ mpg) |>
  mark_rect() |>
  transform('bin', thresholdsX = 10, thresholdsY = 10)
```

## symmetryY (mirror)

Create a symmetric / butterfly chart.

```{r}
df = data.frame(
  x = rep(c('A', 'B', 'C'), each = 2), y = c(3, 2, 5, 4, 1, 6),
  color = rep(c('Male', 'Female'), 3)
)
g2(df, y ~ x, color = ~ color) |>
  mark_interval() |>
  transform('stackY') |>
  transform('symmetryY')
```

## sortX / sortY

Sort data before rendering.

```{r}
df = data.frame(x = c('C', 'A', 'B'), y = c(2, 5, 3))
g2(df, y ~ x) |>
  transform('sortX', reverse = TRUE)
```

## Multiple transforms

Transforms can be chained. Order matters.

```{r}
p |>
  transform('stackY') |>
  transform('normalizeY') |>
  coord_transpose()
```
