首页 > 解决方案 > 使链接的颜色与 Sankey Plot、R 中的 Plotly 中的源节点相同

问题描述

所以我在桑基图的r文档中没有找到任何明确的解决方案,希望有人能帮助我!我要做的就是使链接与源节点的颜色相同,并在将鼠标悬停在其上方时使链接变暗。这是我目前存在的桑基图,不幸的是,由于存在一些保密问题,我无法共享数据。在底部,您会找到我所拥有的情节图像的链接。

dt <- setDT(copy(dt_minors2016))
nodes <- dt[,unique(c(citizen,geo))]
sources <- match(dt[,citizen],nodes)-1
targets <- match(dt[,geo], nodes) -1
values <- dt[,V1]

fig <- plot_ly(
  type = "sankey",
  #default= 1000,
  domain = list(
    x =  c(0,1),
    y =  c(0,1)
  ),
  orientation = "h",
  valueformat = ".0f",
  valuesuffix = "Persons",
  
  node = list(
    label = nodes,
    # color = colors,
    pad = 15,
    thickness = 15,
    line = list(
      color = "black",
      width = 0.5
    )
  ),
  
  link = list(
    source = sources,
    target = targets,
    value =  values,
    color = 'rgba(0,255,255,0.4)'
  )
)
fig <- fig %>% layout(
  title = "UAM asylum seekers from top 5 origin countries to EU countries - 2016",
  font = list(
    size = 10
  ),
  xaxis = list(showgrid = F, zeroline = F),
  yaxis = list(showgrid = F, zeroline = F),
  hovermode = "x unified"
)

fig

https://i.stack.imgur.com/oAMh8.png

标签: pythonrplotlysankey-diagram

解决方案


  • 根据评论,python中提供的解决方案不是R
  • 解决方案的核心是使用与名称关联的imdex节点链接上设置颜色,以从预定义的颜色列表中选择颜色
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
import itertools

df = pd.DataFrame(
    itertools.product(
        ["AF", "SY", "IQ", "SO", "ER"], ["DE", "AT", "BG", "SE", "UK", "CH"]
    ),
    columns=["source", "target"],
).pipe(lambda d: d.assign(value=np.random.uniform(1, 10000, 1000)[:len(d)]))

nodes = np.unique(df[["source", "target"]], axis=None)
nodes = pd.Series(index=nodes, data=range(len(nodes)))

fig = go.Figure(
    go.Sankey(
        node={
            "label": nodes.index,
            "color": [
                px.colors.qualitative.Plotly[i % len(px.colors.qualitative.Plotly)]
                for i in nodes
            ],
        },
        link={
            "source": nodes.loc[df["source"]],
            "target": nodes.loc[df["target"]],
            "value": df["value"],
            "color": [
                px.colors.qualitative.Plotly[i % len(px.colors.qualitative.Plotly)]
                for i in nodes.loc[df["source"]]
            ],
        },
    )
)

fig

在此处输入图像描述


推荐阅读