python - 使链接的颜色与 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
解决方案
- 根据评论,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
推荐阅读
- r - 绘制由两个变量分组的数据框的堆积条形图
- python - 轴旋转
- azure - 如何将 Azure 认知搜索结果存储到 Cosmos DB
- reactjs - 使用 immer 时如何更新渲染中的状态对象
- mdx - EXISTS 函数的用法?
- javascript - 当初始化器也是循环设置器时,如何保持循环干燥?
- mysql - 您如何以 5 分钟为增量对它们进行分组?
- ip-address - 如何使用 xip?
- flutter - “目前配置的 Flutter SDK 不知道是否完全支持。请更新你的 SDK 并重启 IntelliJ”
- matlab - 如何将此 MATLAB 脚本转换为 SCILAB?