'3D plot with multiple curves of data (frequency spectra) and color gradients to highlight the z-axis (magnitudes)

I'm trying to plot a series of frequency spectra in a 3D space using PolyCollection. My goal is to set "facecolors" as a gradient, i.e., the higher the magnitude, the lighter the color.

Please see this image for reference (I am not looking for the fancy design, just the gradients).

I tried to use the cmap argument of the PollyCollection, but I was unsuccessful. I came this far with the following code adapted from here:

import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import axes3d
import numpy as np
from scipy.ndimage import gaussian_filter1d


def plot_poly(magnitudes):
  freq_data = np.arange(magnitudes.shape[0])[:,None]*np.ones(magnitudes.shape[1])[None,:]
  mag_data = magnitudes
  rad_data = np.linspace(1,magnitudes.shape[1],magnitudes.shape[1])

  verts = []
  for irad in range(len(rad_data)):
      xs = np.concatenate([[freq_data[0,irad]], freq_data[:,irad], [freq_data[-1,irad]]])
      ys = np.concatenate([[0],mag_data[:,irad],[0]])
      verts.append(list(zip(xs, ys)))

  poly = PolyCollection(verts, edgecolor='white', linewidths=0.5, cmap='Greys')
  poly.set_alpha(.7)

  fig = plt.figure(figsize=(24, 16))
  ax = fig.add_subplot(111, projection='3d', proj_type = 'ortho')
  ax.add_collection3d(poly, zs=rad_data, zdir='y')

  ax.set_xlim3d(freq_data.min(), freq_data.max())
  ax.set_xlabel('Frequency')
  ax.set_ylim3d(rad_data.min(), rad_data.max())
  ax.set_ylabel('Measurement')
  ax.set_zlabel('Magnitude')

  # Remove gray panes and axis grid
  ax.xaxis.pane.fill = False
  ax.xaxis.pane.set_edgecolor('white')
  ax.yaxis.pane.fill = False
  ax.yaxis.pane.set_edgecolor('white')
  ax.zaxis.pane.fill = False
  ax.zaxis.pane.set_edgecolor('white')

  ax.view_init(50,-60)

  plt.show()


sample_data = np.random.rand(2205, 4)
sample_data = gaussian_filter1d(sample_data, sigma=10, axis=0) # Just to smoothe the curves

plot_poly(sample_data)

Besides the missing gradients I am happy with the output of the code above.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source