16

I am trying to create a simple 3D scatter plot but I want to also show a 2D projection of this data on the same figure. This would allow to show a correlation between two of those 3 variables that might be hard to see in a 3D plot.

I remember seeing this somewhere before but was not able to find it again.

Here is some toy example:

x= np.random.random(100)
y= np.random.random(100)
z= sin(x**2+y**2)

fig= figure()
ax= fig.add_subplot(111, projection= '3d')
ax.scatter(x,y,z)
Labibah
  • 5,371
  • 6
  • 25
  • 23

2 Answers2

31

You can add 2D projections of your 3D scatter data by using the plot method and specifying zdir:

import numpy as np
import matplotlib.pyplot as plt

x= np.random.random(100)
y= np.random.random(100)
z= np.sin(3*x**2+y**2)

fig= plt.figure()
ax= fig.add_subplot(111, projection= '3d')
ax.scatter(x,y,z)

ax.plot(x, z, 'r+', zdir='y', zs=1.5)
ax.plot(y, z, 'g+', zdir='x', zs=-0.5)
ax.plot(x, y, 'k+', zdir='z', zs=-1.5)

ax.set_xlim([-0.5, 1.5])
ax.set_ylim([-0.5, 1.5])
ax.set_zlim([-1.5, 1.5])

plt.show()

enter image description here

Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • Is there a way to do this with imshow or contour instead of plot? When using contour, I can't seem to decouple the contour values (which should be projected densities) from the `zdir` dimension values. In your example, the contour (say, from a histogram) might have values in the range [0, 5], but your axes range from [-.5, 1.5] – paradiso May 17 '15 at 20:36
  • 2
    `ax.plot(..)` should be called before `ax.scatter(..)`. Otherwise the projections are *in front* of the scatter data points (unless this is the wanted behaviour). – steffen Jun 07 '18 at 06:26
  • instead of the three ax.plot(x, z, 'r+', zdir='y', zs=1.5), I'd like to have ax.fill_between(x, z), but PolyCollection doesn not support it. Any idea how to overcome it? – giammi56 Sep 23 '20 at 19:28
  • Is it possible to do this in such a way that it dynamically changes xs/ys/zs according to where the 3D axes are? – Translunar Aug 16 '21 at 17:47
  • What does the zs = -1.5 do? – Coding_Day Aug 23 '22 at 14:59
7

The other answer works with matplotlib 0.99, but 1.0 and later versions need something a bit different (this code checked with v1.3.1):

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

x= np.random.random(100)
y= np.random.random(100)
z= np.sin(3*x**2+y**2)

fig= plt.figure()
ax = Axes3D(fig)
ax.scatter(x,y,z)

ax.plot(x, z, 'r+', zdir='y', zs=1.5)
ax.plot(y, z, 'g+', zdir='x', zs=-0.5)
ax.plot(x, y, 'k+', zdir='z', zs=-1.5)

ax.set_xlim([-0.5, 1.5])
ax.set_ylim([-0.5, 1.5])
ax.set_zlim([-1.5, 1.5])

plt.show() 

You can see what version of matplotlib you have by importing it and printing the version string:

import matplotlib
print matplotlib.__version__
Noise in the street
  • 589
  • 1
  • 6
  • 20