向Plotly Scatter3d()图中添加特定线条

15
我有一个Plotly的Scatter3d()图,我想在其中绘制一些线条。从物理上讲,我有一个网络,其中有一些节点通过键连接,我想绘制这些键。我该怎么做? Scatter3d()带有一个mode='lines+markers'选项,它可以将其变为点和线的散点图,而不是默认的只有点的散点图。但这不是我想要的。我想提供一组xyz坐标对,并在最后得到一组线。
这是我用于绘制简单Scatter3d()图的函数:
def Splot3dPlotly(xyz):
'''
3D scatter plot using Plotly.

:param xyz: (NPx3) array of xyz positions
:return: A Plotly figure that can now be plotted as usual.
'''
xyz = np.reshape(xyz, (int(xyz.size/3), 3))
NN = int(sqrt(xyz.shape[0]))

trace1 = go.Scatter3d(
    x=xyz[:,0],
    y=xyz[:,1],
    z=xyz[:,2],
    mode = 'markers', # 'lines+markers',
    marker=dict(color=range(NN*NN), colorscale='Portland')
            )

data = [trace1]
layout = go.Layout(
    margin=dict(
        l=0,
        r=0,
        b=0,
        t=0
    )
)

fig = go.Figure(data=data, layout=layout)
return fig
1个回答

19

你可以添加第二个跟踪线,并在每个坐标对之间使用None进行分隔,以防止 Plotly 连接跟踪线。

import plotly.graph_objs as go
import plotly
plotly.offline.init_notebook_mode()

#draw a square
x = [0, 1, 0, 1, 0, 1, 0, 1]
y = [0, 1, 1, 0, 0, 1, 1, 0]
z = [0, 0, 0, 0, 1, 1, 1, 1]

#the start and end point for each line
pairs = [(0,6), (1,7)]

trace1 = go.Scatter3d(
    x=x,
    y=y,
    z=z,
    mode='markers',
    name='markers'
)

x_lines = list()
y_lines = list()
z_lines = list()

#create the coordinate list for the lines
for p in pairs:
    for i in range(2):
        x_lines.append(x[p[i]])
        y_lines.append(y[p[i]])
        z_lines.append(z[p[i]])
    x_lines.append(None)
    y_lines.append(None)
    z_lines.append(None)

trace2 = go.Scatter3d(
    x=x_lines,
    y=y_lines,
    z=z_lines,
    mode='lines',
    name='lines'
)

fig = go.Figure(data=[trace1, trace2])
plotly.offline.iplot(fig, filename='simple-3d-scatter')

在此输入图片描述


3
我会接受这个答案,因为没有其他的,但 Plotly 真的应该考虑包含一种更简便的绘制三维线条的方法。类似于 matplotlib 的 LineCollection 就是理想的选择。 - ap21
1
@ap21:我同意,添加“None”相当不专业。我看到你在Plotly论坛上请求该功能,希望他们能听到你的声音! - Maximilian Peters
2
@MaximilianPeters,感谢您的回答。您救了我的一天 <3 - Jaroslav Bezděk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接