3

Is it possible to use the ggridges package to draw sets of bars instead of ridgelines, similar to geom_col()?

I have data such as:

dt = tibble(
    hr = c(1,2,3,4,1,2,3,4),
    fr = c(.1,.5,.9,.1,.4,.9,.9,.4),
    gr = c('Mon','Mon','Mon','Mon','Sun','Sun','Sun','Sun')
)

The plot below gives me:

ggplot(dt, aes(x=hr, y=gr, height=fr)) + 
  geom_ridgeline() + ylab(NULL)

enter image description here

As you can see it draws a line connecting the values. What I am looking for instead are individual columns, as in this plot:

ggplot(dt, aes(x=hr, y=fr)) + 
  geom_col() + ylab(NULL) +
  facet_wrap(~gr)

enter image description here

Marcus Campbell
  • 2,746
  • 4
  • 22
  • 36
kbk78
  • 139
  • 4
  • _"I need it be represent a constant height between the x values."_ I don't understand what that means. Perhaps you can draw what you actually want. Are you looking for a smoothed version of `geom_ridgeline`? – Axeman Dec 01 '17 at 14:11
  • Sorry for the half baked question. I updated the question – kbk78 Dec 01 '17 at 14:51
  • Please provide an [MCVE.](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Claus Wilke Dec 02 '17 at 05:52
  • Two comments: 1. Have you looked into `stat_binline()`? Does it help? 2. You can simulate bars by tracing them out, lower left corner, upper left, upper right, lower right. That's what `stat_binline()` does. – Claus Wilke Dec 03 '17 at 01:14

1 Answers1

4

Here is a solution tracing out the individual bars.

library(tidyverse)
library(ggridges)

dt = tibble(
  hr = c(1,2,3,4,1,2,3,4),
  fr = c(.1,.5,.9,.1,.4,.9,.9,.4),
  gr = c('Mon','Mon','Mon','Mon','Sun','Sun','Sun','Sun')
)

# function that turns an x, y pair into the shape of a bar of given width
make_bar <- function(x, y, width = 0.9) {
  xoff <- width/2
  data.frame(x = c(x-xoff*(1+2e-8), x-xoff*(1+1e-8), x-xoff, x+xoff, x+xoff*(1+1e-8), x+xoff*(1+2e-8)),
             height = c(NA, 0, y, y, 0, NA))
}

# convert data table using make_bar function
dt %>%
  mutate(bars = map2(hr, fr, ~make_bar(.x, .y))) %>%
  unnest() -> dt_bars

ggplot(dt_bars, aes(x=x, y=gr, height=height)) + 
  geom_ridgeline() + ylab(NULL)

enter image description here

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104