Plotly:如何使用 plotly.graph_objects 将两个 3D 图放在同一个图上?
Posted
技术标签:
【中文标题】Plotly:如何使用 plotly.graph_objects 将两个 3D 图放在同一个图上?【英文标题】:Plotly: How to put two 3D graphs on the same plot with plotly.graph_objects? 【发布时间】:2021-02-16 23:50:03 【问题描述】:在下面的代码中,我用plotly.graph_objects
绘制了 2 个 3D 图形。我无法将它们放在一起。
import plotly.graph_objects as go
import numpy as np
pts = np.loadtxt(np.DataSource().open('https://raw.githubusercontent.com/plotly/datasets/master/mesh_dataset.txt'))
x, y, z = pts.T
### First graph
fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z,
alphahull=5,
opacity=0.4,
color='cyan')])
fig.show()
#######
x = [0, 1, 0]
y = [0, 2, 3]
tvects = [x,y]
orig = [0,0,0]
df=[]
coords = [[orig, np.sum([orig, v],axis=0)] for v in tvects]
for i,c in enumerate(coords):
X1, Y1, Z1 = zip(c[0])
X2, Y2, Z2 = zip(c[1])
vector = go.Scatter3d(x = [X1[0],X2[0]],
y = [Y1[0],Y2[0]],
z = [Z1[0],Z2[0]],
marker = dict(size = [0,5],
color = ['blue'],
line=dict(width=5,
color='DarkSlateGrey')),
name = 'Vector'+str(i+1))
data.append(vector)
### Second graph
fig = go.Figure(data=data)
fig.show()
########
您能否详细说明如何做到这一点,以及如何在第二张图中使用带头的箭头而不是线?
【问题讨论】:
【参考方案1】:如果您想在您的第一个 fig
定义的基础上构建,只需在您第一次调用 go.Figure()
后添加以下内容
data = fig._data
data
现在是一个列表,它将在您已经存在的代码的其余部分中附加新元素:
for i,c in enumerate(coords):
X1, Y1, Z1 = zip(c[0])
X2, Y2, Z2 = zip(c[1])
vector = go.Scatter3d(<see details in snippet below>)
data.append(vector)
结果:
关于箭头,您可以通过go.Scatter3D
直接获得的唯一选项是:
['circle', 'circle-open', 'square', 'square-open','diamond', 'diamond-open', 'cross', 'x']
我希望其中一个选项能满足您的需求。您可以指定其中一个:
marker = dict(size = [15,15],
color = ['blue'],
symbol = 'diamond',
line=dict(width=500,
#color='red'
)),
完整代码:
import plotly.graph_objects as go
import numpy as np
pts = np.loadtxt(np.DataSource().open('https://raw.githubusercontent.com/plotly/datasets/master/mesh_dataset.txt'))
x, y, z = pts.T
### First graph
fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z,
alphahull=5,
opacity=0.4,
color='cyan')])
#fig.show()
#######
data = fig._data
x = [0, 1, 0]
y = [0, 2, 3]
tvects = [x,y]
orig = [0,0,0]
df=[]
coords = [[orig, np.sum([orig, v],axis=0)] for v in tvects]
# ['circle', 'circle-open', 'square', 'square-open','diamond', 'diamond-open', 'cross', 'x']
for i,c in enumerate(coords):
X1, Y1, Z1 = zip(c[0])
X2, Y2, Z2 = zip(c[1])
vector = go.Scatter3d(x = [X1[0],X2[0]],
y = [Y1[0],Y2[0]],
z = [Z1[0],Z2[0]],
marker = dict(size = [15,15],
color = ['blue'],
symbol = 'diamond',
line=dict(width=500,
#color='red'
)),
name = 'Vector'+str(i+1))
data.append(vector)
### Second graph
fig = go.Figure(data=data)
fig.show()
########
【讨论】:
请问如何为每个向量设置一个箭头? @LAD 还没有找到实现箭头的方法,但至少你还有其他选择。看看我上次的编辑。以上是关于Plotly:如何使用 plotly.graph_objects 将两个 3D 图放在同一个图上?的主要内容,如果未能解决你的问题,请参考以下文章
ModuleNotFoundError:没有名为“plotly.graph_objects”的模块
如何使用 plotly.graph_object 在仪表图上添加图例