【问题标题】:Making the color of links the same as source nodes in Sankey Plot, Plotly in R使链接的颜色与 Sankey Plot、R 中的 Plotly 中的源节点相同
【发布时间】:2021-11-28 07:20:32
【问题描述】:

所以我在桑基图的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

【问题讨论】:

  • 我有一个解决方案 - 它在 python 中,我不倾向于在 R 中重新编码。它是有情节的,所以 R 中的方法将相同,只是语言语法略有不同。如果您也更新问题以接受 python,我可以提供答案
  • 非常感谢您的回复!刚刚编辑了标签,所以现在应该可以工作了:)
  • Here 你可以找到一个使用 plotly 的 R api 的例子。

标签: python r plotly sankey-diagram


【解决方案1】:
  • 根据 cmets,python 中提供的解决方案不是 R
  • 解决方案的核心是使用与名称关联的 imdexnodeslinks 上设置 color预定义颜色列表中的颜色
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    相关资源
    最近更新 更多