gpt4 book ai didi

python - 如何在网络风格的 Plotly 图中设置单独的线宽(Python 3.6 | plot.ly)?

转载 作者:太空狗 更新时间:2023-10-30 01:32:02 24 4
gpt4 key购买 nike

我正在为改编自 https://plot.ly/python/network-graphs/ 的 networkx 图开发 plot.ly 包装器.我不知道如何根据权重更改每个连接的宽度。权重在 attr_dict 中作为 weight。我尝试设置 go.Line 对象,但它没有用 :(。有什么建议吗?(如果可能,还有指向教程的链接 :))。附上我在 matplotlib 中绘制的网络结构示例。

如何在 plotly 中为每个连接设置单独的线宽?

enter image description here

import requests
from ast import literal_eval
import plotly.offline as py
from plotly import graph_objs as go
py.init_notebook_mode(connected=True)

# Import Data
pos = literal_eval(requests.get("https://pastebin.com/raw/P5gv0FXw").text)
df_plot = pd.DataFrame(pos).T
df_plot.columns = list("xy")
edgelist = literal_eval(requests.get("https://pastebin.com/raw/2a8ErW7t").text)
_fig_kws={"figsize":(10,10)}

# Plotting Function
def plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws):
# Nodes
node_trace = go.Scattergl(
x=df_plot["x"],
y=df_plot["y"],
mode="markers",
)
# Edges
edge_trace = go.Scattergl(
x=[],
y=[],
line=[],
mode="lines"
)

for node_A, node_B, attr_dict in edgelist:
xA, yA = pos[node_A]
xB, yB = pos[node_B]
edge_trace["x"] += [xA, xB, None]
edge_trace["y"] += [yA, yB, None]
edge_trace["lines"].append(go.Line(width=attr_dict["weight"],color='#888'))

# Data
data = [node_trace, edge_trace]
layout = {
"width":_fig_kws["figsize"][0]*100,
"height":_fig_kws["figsize"][1]*100,

}
fig = dict(data=data, layout=layout)

py.iplot(fig)
return fig
plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws)

# ---------------------------------------------------------------------------
# PlotlyDictValueError Traceback (most recent call last)
# <ipython-input-72-4a5d0e26a71d> in <module>()
# 46 py.iplot(fig)
# 47 return fig
# ---> 48 plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws)

# <ipython-input-72-4a5d0e26a71d> in plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws)
# 25 y=[],
# 26 line=[],
# ---> 27 mode="lines"
# 28 )
# 29

# ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in __init__(self, *args, **kwargs)
# 375 d = {key: val for key, val in dict(*args, **kwargs).items()}
# 376 for key, val in d.items():
# --> 377 self.__setitem__(key, val, _raise=_raise)
# 378
# 379 def __dir__(self):

# ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in __setitem__(self, key, value, _raise)
# 430
# 431 if self._get_attribute_role(key) == 'object':
# --> 432 value = self._value_to_graph_object(key, value, _raise=_raise)
# 433 if not isinstance(value, (PlotlyDict, PlotlyList)):
# 434 return

# ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in _value_to_graph_object(self, key, value, _raise)
# 535 if _raise:
# 536 path = self._get_path() + (key, )
# --> 537 raise exceptions.PlotlyDictValueError(self, path)
# 538 else:
# 539 return

# PlotlyDictValueError: 'line' has invalid value inside 'scattergl'

# Path To Error: ['line']

# Current path: []
# Current parent object_names: []

# With the current parents, 'line' can be used as follows:

# Under ('figure', 'data', 'scattergl'):

# role: object

更新 Ian Kent 的回答:

我不认为下面的代码可以改变所有行的权重。我尝试使用 weights 列表制作所有宽度 0.1 并得到以下图: enter image description here

但是当我执行 width=0.1 时,它适用于所有行: enter image description here

最佳答案

我认为问题出在您的代码的以下行中:

edge_trace["lines"].append(go.Line(width=attr_dict["weight"],color='#888'))

试试用“line”代替“lines”。这是 Plotly API 的一个有点令人困惑的方面,但在散点图中,模式是复数,而用于更改轨迹属性的参数名称是单数。所以,

trace = go.Scatter(mode = 'markers', marker = dict(...))
trace = go.Scatter(mode = 'lines', line = dict(...))

编辑:好的,现在我已经坐下来解决了问题,而不仅仅是“台词”:

您将 line 参数作为类似 dict 的对象列表,而 plotly 期望它是一个类似 dict 的对象。构建一个权重列表,然后立即将所有权重添加到 line 属性似乎可行:

edge_trace = go.Scattergl(
x=[],
y=[],
mode="lines"
)

weights = []
for node_A, node_B, attr_dict in edgelist:
xA, yA = pos[node_A]
xB, yB = pos[node_B]
edge_trace["x"] += [xA, xB, None]
edge_trace["y"] += [yA, yB, None]
weights.append(attr_dict["weight"])

edge_trace['line'] = dict(width=weights,color='#888')

此外,您在节点前面绘制线条并因此阻碍了它们。你应该改变

data = [node_trace, edge_trace]

data = [edge_trace, node_trace]

避免这种情况。

关于python - 如何在网络风格的 Plotly 图中设置单独的线宽(Python 3.6 | plot.ly)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46374106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com