Combine Sankeynetwork plot with a normal ggplot

Viewed 231

Problem:

Is it possible to combine a sankeyNetwork plot and a normal ggplot?

I've tried using ggarrange, which returns the following error:

> ggarrange(p1, p2, rremove("x.text"), ncol = 1, nrow = 2)
$`1`

$`2`

attr(,"class")
[1] "list"      "ggarrange"
Warning messages:
1: In as_grob.default(plot) :
  Cannot convert object of class sankeyNetworkhtmlwidget into a grob.
2: In as_grob.default(plot) :
  Cannot convert object of class themegg into a grob.

and cowplot, which returns the following error:

> plot_grid(p1, p2, ncol = 1, align = 'v', axis = 'l', rel_widths = c(3,1))
Warning message:
In as_grob.default(plot) :
  Cannot convert object of class sankeyNetworkhtmlwidget into a grob.

It seems like in both instances the commands need to work with two grob files but are unable to convert the sankeyNetwork plot into this format.

Ideally i'd retain the interactive elements of the sankeyNetwork plot as I have about 10 categories in each column of my graph and with each flowing into the next this means 100 flows. As some of these are quite small, but still not insignificant, being able to hover over and highlight them is key for being able to see the patterns between nodes.

Ultimately I also want the bar chart to be only approximately 1/3 the height of the Sankey plot, and stacked on top.

For a reproducible example:

You can use this code to make a Sankey plot (source):

# Load package
library(networkD3)
 
# Load energy projection data
URL <- "https://cdn.rawgit.com/christophergandrud/networkD3/master/JSONdata/energy.json"
Energy <- jsonlite::fromJSON(URL)

 
# Now we have 2 data frames: a 'links' data frame with 3 columns (from, to, value), and a 'nodes' data frame that gives the name of each node.
head( Energy$links )
head( Energy$nodes )
 
# Thus we can plot it
p1 <- sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "name",
              units = "TWh", fontSize = 12, nodeWidth = 30)
p1

which produces an interactive version of: enter image description here

And this code to make a regular ggplot plot:

p2 <- ggplot(mpg, aes(class)) + geom_bar()
p2

which produces:

enter image description here

0 Answers
Related