I would like to construct a stacked bar plot (or arrow plot), preferably using ggplot2
, with the example data d
below, for each id
.
The peculiarity is that I would like for the stack to follow the columns order v0
first, z1
second, and z2
third (data is in wide format). Notice however that z2
has some negative values. So it should somehow be represented by an arrow or something, from the top of the stack going down (or up, depending on the value of z3
).
Is there a way to do this?
d <- data.frame(
id=c('AAA','BBB','CCC','DDD','EEE','FFF'),
v0 =c( 50 , 60 , 40 , 50 , 70 ,40),
z1 =c( 20 , 15 , 5 , 40 , 5 , 40),
z2 =c(-10 , 5 , 10 ,-20 , 15 ,-15)
)
#normaly people transform the data to long format:
d %>% gather(ef_type, value,v0:d2) %>%
ggplot(aes(...) + geom_bar(...)
OBS: Notice that this is different from the answer to this related question, in which the order of the columns does not matter, and the negative values are represented in the negative part of the y-axis.
EDIT1: based on @fanli answer bellow I tried the following code:
d %>% select(id,v0,z1) %>% gather(ef_type, value,v0:z1) -> df
d %>% mutate(z2_start=v0+z1,z2_end=v0+z1+z2) %>% select(id,z2_start,z2_end) -> df2
ggplot(df, aes(x=id,y=value,fill=ef_type))+ geom_bar(stat = "identity") +
+ geom_segment(data=df2, aes(x=id, xend=id, y=z2_start, yend=z2_end), arrow = arrow(length = unit(0.02, "npc")))
#which results in the error:
Error: ggplot2 doesn't know how to deal with data of class uneval