3

I occasionally see diagrams where two 2-dimensional scatterplots are superimposed on one another in a 3D space so that corresponding points can be linked. Frequently these take the form of networks where the two networks overlayed. For example:

enter image description here reference: https://satijalab.org/seurat/v3.0/pbmc3k_tutorial.html

enter image description here reference: https://image.slidesharecdn.com/2007mauricioarango-end-to-endqosviaoverlaynetworksandbandwidthon-demand-091102230540-phpapp02/95/providing-endtoend-network-qos-via-overlay-networks-and-bandwidth-ondemand-mauricio-arango-2007-5-728.jpg?cb=1257203157

I know I could arbitrarily add a common 3rd dimension to two dimensional plots to get a plot like this:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

def randrange(n, vmin, vmax):
    return (vmax - vmin)*np.random.rand(n) + vmin

n = 100

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = np.append(np.repeat(1, 50), np.repeat(2, 50))

for c, m in [('r', 'o'), ('b', '^')]:
     ax.scatter(xs, ys, zs, c=c, marker = m)

enter image description here

and then connect the relevant points but I thought there might be a more straightforward way to construct such images in either R or python?

zx8754
  • 52,746
  • 12
  • 114
  • 209
G_T
  • 1,555
  • 1
  • 18
  • 34

1 Answers1

0

I did not find anything straightforward in matplotlib. One possible solution is to use quiver:

from mpl_toolkits.mplot3d import Axes3D  # keep it for projection='3d'
import matplotlib.pyplot as plt
import random


def calculate_vectors(x0, y0, z0, x1, y1, z1):
    u = []
    v = []
    w = []
    for i, x in enumerate(x0):
        dx = x1[i] - x
        dy = y1[i] - y0[i]
        dz = z1[i] - z0[i]
        u.append(dx)
        v.append(dy)
        w.append(dz)
    return u, v, w


def make_plot():
    n = 20
    x1 = [random.randrange(23, 32, 1) for _ in range(n)]
    y1 = [random.randrange(0, 100, 1) for _ in range(n)]
    z1 = [1.0 for _ in range(n)]

    x2 = [random.randrange(23, 32, 1) for _ in range(n)]
    y2 = [random.randrange(0, 100, 1) for _ in range(n)]
    z2 = [2.0 for _ in range(n)]

    u, v, w = calculate_vectors(x1, y1, z1, x2, y2, z2)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.scatter(x1, y1, z1, c='b', marker='^')
    ax.scatter(x2, y2, z2, c='r', marker='o')
    ax.quiver(x1, y1, z1, u, v, w, arrow_length_ratio=0.0)


make_plot()
plt.show()

I didn't use numpy as it was more fun to refresh vectors and sin/cos calculations. Here is the output:

enter image description here

Alex Lopatin
  • 682
  • 4
  • 8