Align bins vertically with stat_histinterval

44 Views Asked by At

I am trying to create a faceted plot showing multiple group density distributions and histograms in the same facet, but I'm having trouble customizing the bins on the histograms, which were created using stat_histinterval. I have altered the bin width to be consistent across plots (breaks = breaks_fixed(width = .2)), but notice that in the bottom left facet the bins have a different alignment. I know there are alignment arguments for stat_histinterval, but they don't seem to be working vertically. Can someone help me align the bins either with a starting value or a centered value?

Here is my code:

library(ggplot2)
library(ggdist)

data <- mtcars
data$cyl <- as.factor(data$cyl)
ggplot(data, aes(y = wt , col = cyl, group = cyl, fill = cyl))+
  stat_halfeye(
    slab_color = "gray45",
    alpha = .2
  ) +
  stat_histinterval(
    slab_type = "histogram",
    slab_color = "gray45",
    side = "left",
    alpha = .2,
    outline_bars = TRUE,
    breaks = breaks_fixed(width = .2)
  ) +
  facet_grid(vs ~ am) +
  labs(x = "Density")
1

There are 1 best solutions below

0
Matthew Kay On

align should work whether the geom is horizontal or vertical. On your example this works:

library(ggplot2)
library(ggdist)

data <- mtcars
data$cyl <- as.factor(data$cyl)
ggplot(data, aes(y = wt , col = cyl, group = cyl, fill = cyl))+
  stat_halfeye(
    slab_color = "gray45",
    alpha = .2
  ) +
  stat_histinterval(
    slab_color = "gray45",
    side = "left",
    alpha = .2,
    outline_bars = TRUE,
    breaks = breaks_fixed(width = .2),
    align = align_boundary(at = 0)
  ) +
  facet_grid(vs ~ am) +
  labs(x = "Density")

faceted histograms

(I also dropped slab_type = "histogram" from your call to stat_histinterval() as it is deprecated).