Home > Blockchain >  ggplot sankey diagram of income to expenses (ggsankey)
ggplot sankey diagram of income to expenses (ggsankey)

Time:10-31

I am trying to make an income to expenses sankey diagram, preferably with ggsankey or another ggplot extension, because I need the final plot as an image (png). Here is my data:

data <- tibble::tribble(
                 ~Name, ~Annual.Amount,  ~Category,
    "Moira's Earnings",         50000L,   "Income",
   "Johnny's Earnings",        300000L,   "Income",
     "Living Expenses",        140000L, "Expenses",
       "Spent Savings",         25238L, "Expenses",
         "Liabilities",         44280L, "Expenses",
     "Planned Savings",         23000L, "Expenses",
               "Taxes",         98482L, "Expenses",
           "Insurance",         13000L, "Expenses"
  )

I am trying to create something like this diagram, but with only the first 2 flows, all income into one column from where the expenses flow: enter image description here

CodePudding user response:

library(tidyverse)
library(networkD3)

data <- tibble::tribble(
  ~Name, ~Annual.Amount,  ~Category,
  "Moira's Earnings",         50000L,   "Income",
  "Johnny's Earnings",        300000L,   "Income",
  "Living Expenses",        140000L, "Expenses",
  "Spent Savings",         25238L, "Expenses",
  "Liabilities",         44280L, "Expenses",
  "Planned Savings",         23000L, "Expenses",
  "Taxes",         98482L, "Expenses",
  "Insurance",         13000L, "Expenses"
)

Nodes = tibble(
  Name = c(data$Name, "Budget") %>% unique()
) %>% as.data.frame()


df = data %>% filter(Category=="Income") %>%
  select(-Category) %>%
  rename(Source = Name) %>%
  mutate(Target = "Budget") %>%
  bind_rows(
    data %>%
      filter(Category=="Expenses") %>%
      select(-Category) %>%
      rename(Target = Name) %>%
      mutate(Source = "Budget")
  ) %>% mutate(
  IDSource = match(Source, Nodes$Name)-1,
  IDTarget = match(Target, Nodes$Name)-1
) %>% as.data.frame()

sankeyNetwork(Links = df, Nodes = Nodes,
              Source = "IDSource", Target = "IDTarget",
              Value = "Annual.Amount", NodeID = "Name",
              sinksRight=FALSE, fontSize = 16)

enter image description here

Small update

library(webshot)
webshot::install_phantomjs()
sankeyNetwork(Links = df, Nodes = Nodes,
              Source = "IDSource", Target = "IDTarget",
              Value = "Annual.Amount", NodeID = "Name",
              sinksRight=FALSE, fontSize = 16) %>%
  saveNetwork("sn.html")

webshot("sn.html", "sankeyNetwork.png")

enter image description here

  • Related