Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib 3D scatter plot with color gradient

Tags:

How can I create a 3D plot with a color gradient for the points? See the example below, which works for a 2D scatter plot.

Edit (thanks to Chris): What I'm expecting to see from the 3D plot is a color gradient of the points ranging from red to green as in the 2D scatter plot. What I see in the 3D scatter plot are only red points.

Solution: for some reasons (related to the gradient example I copied elsewhere) I set xrange to len-1, which messes everything in the 3D plot.

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D  # Create Map cm = plt.get_cmap("RdYlGn")  x = np.random.rand(30) y = np.random.rand(30) z = np.random.rand(30) #col = [cm(float(i)/(29)) for i in xrange(29)] # BAD!!! col = [cm(float(i)/(30)) for i in xrange(30)]  # 2D Plot fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(x, y, s=10, c=col, marker='o')    # 3D Plot fig = plt.figure() ax3D = fig.add_subplot(111, projection='3d') ax3D.scatter(x, y, z, s=10, c=col, marker='o')    plt.show() 
like image 374
andrea.ge Avatar asked Jan 17 '12 09:01

andrea.ge


People also ask

Can matplotlib Pyplot be used to display 3D plots?

Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit.

Can we plot 3D graphs in matplotlib?

In order to plot 3D figures use matplotlib, we need to import the mplot3d toolkit, which adds the simple 3D plotting capabilities to matplotlib. Once we imported the mplot3d toolkit, we could create 3D axes and add data to the axes. Let's first create a 3D axes. The ax = plt.

Can you create a Coloured scatter plot using matplotlib?

Matplotlib scatter has a parameter c which allows an array-like or a list of colors. The code below defines a colors dictionary to map your Continent colors to the plotting colors.


1 Answers

Here is an example for 3d scatter with gradient colors:

import matplotlib.cm as cmx from mpl_toolkits.mplot3d import Axes3D def scatter3d(x,y,z, cs, colorsMap='jet'):     cm = plt.get_cmap(colorsMap)     cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs))     scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)     fig = plt.figure()     ax = Axes3D(fig)     ax.scatter(x, y, z, c=scalarMap.to_rgba(cs))     scalarMap.set_array(cs)     fig.colorbar(scalarMap)     plt.show() 

Of course, you can choose the scale to range between different values, like 0 and 1.

like image 114
Noam Peled Avatar answered Sep 20 '22 09:09

Noam Peled