@@ -1028,4 +1028,77 @@ targetcmp_fun <- function(cursum, restoresum, cap){
1028
1028
1029
1029
return (tab )
1030
1030
1031
+ }
1032
+
1033
+ # alluvial plot function, for HMPU targets
1034
+ # https://www.data-to-viz.com/graph/sankey.html
1035
+ alluvout2 <- function (datin , fluccs , mrg ){
1036
+
1037
+ clp <- fluccs %> %
1038
+ pull(HMPU_TARGETS ) %> %
1039
+ unique %> %
1040
+ c(' Coastal Uplands' , . ) %> %
1041
+ sort
1042
+
1043
+ sumdat <- datin %> %
1044
+ rename(Acres = value ) %> %
1045
+ mutate(
1046
+ target = gsub(' ,\\ s[0-9]+$' , ' ' , target ),
1047
+ source = gsub(' ,\\ s[0-9]+$' , ' ' , source )
1048
+ ) %> %
1049
+ group_by(target , source ) %> %
1050
+ summarise(Acres = sum(Acres ), .groups = ' drop' ) %> %
1051
+ na.omit() %> %
1052
+ group_by(target , source ) %> %
1053
+ summarise(Acres = sum(Acres ), .groups = ' drop' ) %> %
1054
+ select(source = source , target = target , value = Acres ) %> %
1055
+ data.frame (stringsAsFactors = F )
1056
+ sumdat $ source <- paste(sumdat $ source , " " , sep = " " )
1057
+
1058
+ # From these flows we need to create a node data frame: it lists every entities involved in the flow
1059
+ nodes <- data.frame (name = c(as.character(sumdat $ source ), as.character(sumdat $ target )) %> % unique())
1060
+
1061
+ # With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
1062
+ sumdat $ IDsource = match(sumdat $ source , nodes $ name )- 1
1063
+ sumdat $ IDtarget = match(sumdat $ target , nodes $ name )- 1
1064
+
1065
+ # custom color scale
1066
+ cols <- c(' #004F7E' , ' #00806E' , ' #427355' , ' #958984' , ' #5C4A42' , ' grey' ) %> %
1067
+ colorRampPalette
1068
+ ncol <- sumdat [, c(' source' , ' target' )] %> %
1069
+ unlist() %> %
1070
+ unique %> %
1071
+ gsub(' \\ s$' , ' ' , . ) %> %
1072
+ unique %> %
1073
+ length()
1074
+ colin <- cols(ncol ) %> %
1075
+ paste(collapse = ' ", "' ) %> %
1076
+ paste(' d3.scaleOrdinal(["' , . , ' "])' )
1077
+
1078
+ # margins for long text labels
1079
+ mrgs <- list (0 , mrg , 0 , 0 )
1080
+ names(mrgs ) <- c(' top' , ' right' , ' bottom' , ' left' )
1081
+
1082
+ out <- sankeyNetwork(Links = sumdat , Nodes = nodes ,
1083
+ Source = " IDsource" , Target = " IDtarget" , colourScale = colin ,
1084
+ Value = " value" , NodeID = " name" , height = 1000 , width = 800 ,
1085
+ sinksRight = FALSE , units = ' acres' , nodeWidth = 50 , fontSize = 13 , nodePadding = 10 ,
1086
+ margin = mrgs )
1087
+
1088
+ out <- htmlwidgets :: onRender(
1089
+ out ,
1090
+ '
1091
+ function(out,x){
1092
+ // select all our node text
1093
+ d3.select(out)
1094
+ .selectAll(".node text")
1095
+ .filter(function(d) { return d.name.endsWith(" "); })
1096
+ .attr("x", x.options.nodeWidth - 55)
1097
+ .attr("text-anchor", "end");
1098
+ }
1099
+ '
1100
+ )
1101
+
1102
+ return (out )
1103
+
1031
1104
}
0 commit comments