我试图用plotly包(plotly_4.10.2)在R中构建三层的Sankey图.虽然从"链接"数据来看,从源到目标的连接似乎是合理的,但plot本身显示的连接不正确.

例如,"www.example.com"—Gene3—Treatment—Catogory2显示为Gene3—Treatment—Category1,Gene8的连接也错误.>在绘图之前,我应该重新排列标签吗?

剧情截图

enter image description here

library(plotly)

# this is an example data

example.data <- data.frame(
  genes = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5", "Gene6", "Gene7", "Gene8", "Gene9"),
  conditions = c("Control", "Control", "Treatment", "Treatment", "Treatment", "Treatment", "Treatment", "Treatment", "Treatment"),
  category = c("Category1", "Category1", "Category2", "Category2", "Category2", "Category2", "Category2", "Category1", "Category2")
)

nodes <- data.frame(name = unique(c(as.character(example.data$genes),
                                    as.character(example.data$conditions),
                                    as.character(example.data$category))))

links <- data.frame(source = match(example.data$genes, nodes$name) - 1,
                    target = match(example.data$conditions, nodes$name) - 1,
                    stringsAsFactors = FALSE)

links <- rbind(links,
               data.frame(source = match(example.data$conditions, nodes$name) - 1,
                          target = match(example.data$category, nodes$name) - 1,
                          stringsAsFactors = FALSE))


plotly::plot_ly(
  type = "sankey",
  domain = list(x =  c(0,1),
                y =  c(0,1)),
  orientation = "h",
  customdata = nodes$name,
  node = list(
    label = nodes$name,
    pad = 15,
    thickness = 15,
    line = list(color = "black",
                width = 0.5)),
  link = list(source = links$source,
              target = links$target,
              value =   rep(1, nrow(links))
  ))

推荐答案

试着按照这个顺序来画:condition -> genes -> category:

nodes <- unique(unlist(example.data))

links <- list(
  source = c(match(example.data$conditions, nodes) - 1, 
             match(example.data$genes, nodes) - 1),
  target = c(match(example.data$genes, nodes) - 1,
             match(example.data$category, nodes) - 1),
  value = rep(1, nrow(example.data) * 2))

plot_ly(type = "sankey",
        node = list(label = nodes),
        link = links)

enter image description here

R相关问答推荐

如何根据包含相同值的某些列获取总额

更改绘图上的x轴断点,而不影响风险?

查找图下的面积

在垂直轴中包含多个ggplot2图中的平均值

警告:lmdif:info = 0. nls. lm()函数的输入参数不正确

在R中替换函数中的特定符号

整数成随机顺序与约束R?

如何写一个R函数来旋转最后n分钟?

筛选出以特定顺序患病的个体

根据文本字符串中的值粘贴新列

如何对2个列表元素的所有组合进行操作?

plotly hover文本/工具提示在shiny 中不起作用

打印XTS对象

使用带有OR条件的grepl过滤字符串

R中边际效应包中Logistic回归的交互作用风险比

从R中发出的咕噜声中的BUG?

数值型数据与字符混合时如何进行绑定

是否有可能从边界中找到一个点值?

使用一个标签共享多个组图图例符号

使用相对风险回归计算RR