我在excel表中有两个相关列的数据: 员工姓名和经理姓名。
我想在R中使用networkD3来创建一个包含此数据的Sankey图表,以显示我们的组织是如何拆分的。我是R的相对业余爱好者,但我已经能够通过对每个节点进行硬编码来生成Sankey图表。是否可以使用我拥有的数据执行此操作?
library(networkD3)
nodes = data.frame("name" =
c(All_Employees$`Employee Name`))
links = as.data.frame(matrix(c(
All_Employees$`Employee Name`,All_Employees$`Manager Name`,1),
byrow = TRUE, ncol = 3))
names(links) = c("source", "target", "value")
sankeyNetwork(Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize= 12, nodeWidth = 30)
答案 0 :(得分:1)
Sankey图表可能不是最好的情节类型,但如果您首先将数据排列成正确的格式,它将起作用...
All_Employees <-
read.csv(header = T, na.strings = "", stringsAsFactors = F, check.names = F,
text = "
Employee Name,Manager Name
Betty,
Tom,Betty
Bob,Betty
Mark,Tom
John,Tom
Sally,Bob")
node_names <- factor(sort(unique(as.character(unname(unlist(All_Employees))))))
nodes <- data.frame(name = node_names)
links <- data.frame(source = match(All_Employees$`Manager Name`, node_names) - 1,
target = match(All_Employees$`Employee Name`, node_names) - 1,
value = 1)
links <- links[!is.na(links$source), ]
library(networkD3)
sankeyNetwork(Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize = 12, nodeWidth = 30)
或者,您可以使用diagonalNetwork()
创建可能更适合的树形图...
library(dplyr)
library(data.tree)
library(networkD3)
All_Employees %>%
filter(!is.na(`Manager Name`)) %>%
data.tree::FromDataFrameNetwork() %>%
data.tree::ToListExplicit(unname = TRUE) %>%
diagonalNetwork()
或者,如果您使用的是networkD3
的开发版本,则可以更轻松地使用新的treeNetwork()
函数,该函数具有更多自定义功能(但仍然存在错误,因为它仍然在开发中)。 ..
library(dplyr)
library(networkD3)
All_Employees %>%
rename(nodeId = `Employee Name`, parentId = `Manager Name`) %>%
mutate(name = nodeId) %>%
treeNetwork(direction = "down", linkType = "elbow")