-1

sample data

Country State   City    Currency    Tasks   Accidents
IND       KR    BLR          INR    1000    500
IND       WB    CCU          INR    2500    200
SL        SL    COL          SLR    500     400
JAP       JAP   TOK          YEN    400    300
AUS       MB    MB            AD    200    4000
AUS       SY    SY            AD    3000    400
AUS       AD    AD            AD    5000    300

Need graph like below which is something like waterfall model ![![Graph requirement][1]][1] Y axis - Country IND SL JAP AUS X axis- Tasks Accidents

tried below two codes

ggplot(df,aes(Country,fill=Value))+
  geom_rect(aes( x = Country,xmin =  Current_no, xmax = Current_no , ymin = Current_no, ymax = Current_no))

Sample data

Country state City flag      value
IND     KA    BLR .  Tasks   8200
IND     WB    CCU    Tasks   2500
IND     KA    BLR .  Accidents 700

p <- plot_ly(
  df_melt, name = "20", type = "waterfall", measure = ~value,
  x = ~Flag, textposition = "outside", y= ~Country, 
  connector = list(line = list(color= "rgb(63, 60, 50, 40, 44, 34, 21)"))) %>%
  layout(title = "Exp Output",
         xaxis = list(title = ""),
         yaxis = list(title = ""),
         autosize = TRUE,
         showlegend = TRUE)
p

Not getting expected output

[1]: https://i.stack.imgur.com/6Mxdo.pngenter image description here

  • 1
    Best path is to include an picture of what you are trying to achieve; either an image on the internet or draw something yourself in Paint (or similar). It's even easier if you draft the plot with pen and paper, using the actual numbers in your sample data to see if the result is even doable. – MrGumble Sep 12 '19 at 11:26
  • @MrGumble Added the image – Anshul Saravgi Sep 12 '19 at 11:38

2 Answers2

1

Not sure whether I'd call it a waterfall plot, but try this on for size:

library(dplyr)
library(tidyr)
library(ggplot2)


df2 <- df %>%
  gather(stat, val, Tasks, Accidents) %>%
  mutate(
    stat=factor(stat, levels=c('Tasks','Accidents')),
    Country = factor(Country, levels=c('IND','SL','JAP','AUS'))
  )

x1 <- df2 %>% group_by(Country, stat) %>% summarise(val=sum(val)) 
x2 <- df2 %>% group_by(stat)  %>% summarise(val=sum(val)) 

ggplot(x1, aes(x=stat, y=val)) + 
  geom_col(aes(fill=Country)) +
  geom_label(data=x2, aes(label=val), nudge_y = 100) +
  theme(legend.position='top')

Not a waterfall plot

Try leaving out the mutate command which converts stat and Country to factors, and see how things change.

MrGumble
  • 5,631
  • 1
  • 18
  • 33
0

try this

  ggplot(x1, aes(x=stat, y=val),fill=Type) + 
    geom_bar(aes(fill=Country),stat = "identity") +
    geom_label(data=x2, aes(label=val), nudge_y = 10,label.padding = unit(0.4, "lines")) +
    scale_y_continuous(labels = scales::percent_format())+
    theme(legend.position='top')+
    geom_label(data=x1, aes(label=val), nudge_y = 10,label.padding = unit(0.1, "lines"))