Search code examples
pythonmatplotlibplotcolorsscatter

3D pyplot scatter opacity by depth


By default, pyplot's 3D plots have depthshade=True. However, in my code I needed to specify the color for each point individually depending on a property of the sample. Consequently, the depth effect is lost.

Is there a way to combine custom colors and the depthshade behavior?

My code for one of the subplots is the following:

fig = plt.figure(figsize=(19.2, 10.8), dpi= 80)
handles = []
for i in range(18):
  handles.append(mlines.Line2D([], [], color=colors_azi[i], marker='.'))
ax = fig.add_subplot(231, projection='3d')
for i in trange(len(outs[1])):
  ax.scatter(outs[0][i], outs[1][i], outs[2][i], c=colors_azi[azimuths[i]//2].reshape(1,-1), depthshade=True)
ax.set_title('Azimuth (train)')

Note that I am reshaping in order to avoid an error from the scatter function, I'm a b it suspicious that this might be the cause but I don't know how to do it otherwise. The plot then look like this, with solid colors:

enter image description here


Solution

  • Okay so at some point I figured out that the issue was doing a scatter per point to map the colors (which also produced a supper laggy behavior in the interactive window).

    The depthsade is applied once per invdividual scatter call. The final code is:

    fig = plt.figure(figsize=(10.8, 10.8), dpi= 80)
    ax = fig.add_subplot(111, projection='3d')
    c1 = []
    for i in range(len(outs[1])):
      c1.append(colors_azi[azimuths[i]//2])
    ax.scatter(outs[0], outs[1], outs[2], color=c1)
    

    Which produces something like this:

    enter image description here