0

I posted here about what I'm trying to achieve Sankey bar graphs in R

I've decided to try and implement this in ggplot, but my current issue is this: Given the code below, how would you go about computing the curves df directly from the main df? Is it possible to extract the centres of the stacked geom_bar elements from the plot itself?

df <- data_frame(a=factor(c(1,2,1,2)), b=factor(c(3,3,4,4)), y = c(20,22,24,18))
p <- df %>% 
  ggplot(aes(x=a, y=y, group=b, fill=b, width=.3)) + 
  geom_bar(stat="identity", alpha=.9)
p

curves = data_frame(x=c(1,1), xend=c(2,2), 
                    y=c(10, 35), yend=c(30,30), 
                    weight=c(40,40),
                    width=c(10,40),
                    b=NA) 

p + 
  geom_curve(data=curves, 
             aes(x=x, y=y, xend=xend, yend=yend, size=weight), 
             curvature=.2, alpha=.4)
Community
  • 1
  • 1
bjw
  • 2,046
  • 18
  • 33
  • [related](http://stackoverflow.com/questions/9968433/sankey-diagrams-in-r) – Axeman Jan 16 '17 at 15:21
  • Perhaps, you may find [this answer](http://stackoverflow.com/a/41655418/3817004) to the Q "Draw lines between different elements in a stacked bar plot" useful. It pulls data from the plot object. – Uwe Jan 16 '17 at 17:04

1 Answers1

0

As a quick example how to get the center of the bars:

library(tidyverse)
curves2 <- df %>% 
  group_by(a) %>% 
  mutate(y = cumsum(y) - 0.5 * y) %>% 
  spread(a, y) %>% 
  rename(y = `1`, yend = `2`) %>% 
  mutate(x = 1, xend = 2)

p + geom_curve(data=curves2, 
             aes(x=x, y=y, xend=xend, yend=yend, fill=NA,group=b), 
             curvature=.2, alpha=.4, size=12)
Axeman
  • 32,068
  • 8
  • 81
  • 94