Question Details

No question body available.

Tags

r ggplot2

Answers (1)

July 23, 2025 Score: 3 Rep: 168,671 Quality: Medium Completeness: 100%

With geomcol(), where there are multiple observations for each x-value:

  • if the y-value is numeric or integer, geomcol() stacks the observations by x (thanks to JonSpring for clarifying this);
  • if the y-value is logical or categorical, it stacks the values by y

Stacking, broken out:

data("mpg", package="ggplot2")
library(ggplot2)
library(dplyr) # just for demonstration

ggplot(mpg, aes(x = hwy, y = cyl)) + geomcol(color = "white")

ggplot grob with geom</em></i>col, changing color to show it is stacked

This looks like summing in a sense (when color/fill is not changed), shown here via explicit aggregation:

summarize(mpg, .by = hwy, cyl = sum(cyl)) |>
  ggplot(aes(x = hwy, y = cyl)) +
  geomcol()

original ggplot created by explicitly summing the cyl value for each unique hwy value

To work around the fact that cyl is numeric or integer, we can force it to be a categorical value with factor(.):

ggplot(mpg, aes(x = hwy, y = factor(cyl))) +
  geomcol()

ggplot of mpg data with cyl as a factor

The "striations" in that shows that it is stacking all of the hwy values in an additive sense (not summing):

slicehead(mpg, by = cyl, n = 3)

# A tibble: 12 × 11

manufacturer model displ year cyl trans drv cty hwy fl class

1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact

2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact

3 audi a4 2 2008 4 manual(m6) f 20 31 p compact

4 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact

5 audi a4 2.8 1999 6 manual(m5) f 18 26 p compact

6 audi a4 3.1 2008 6 auto(av) f 18 27 p compact

7 audi a6 quattro 4.2 2008 8 auto(s6) 4 16 23 p midsize

8 chevrolet c1500 suburban 2wd 5.3 2008 8 auto(l4) r 14 20 r suv

9 chevrolet c1500 suburban 2wd 5.3 2008 8 auto(l4) r 11 15 e suv

10 volkswagen jetta 2.5 2008 5 auto(s6) f 21 29 r compact

11 volkswagen jetta 2.5 2008 5 manual(m5) f 21 29 r compact

12 volkswagen new beetle 2.5 2008 5 manual(m5) f 20 28 r subcompact

slice
head(mpg, by = cyl, n = 3) |> ggplot(aes(x = hwy, y = factor(cyl))) + geom_col(color = "black", fill = "gray")

ggplot of mpg, first three rows for each distinct value of cyl, showing stacked nature of the hwy values