Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib 3D Scatter Plot with Colorbar

Borrowing from the example on the Matplotlib documentation page and slightly modifying the code,

import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt  def randrange(n, vmin, vmax):     return (vmax-vmin)*np.random.rand(n) + vmin  fig = plt.figure() ax = fig.add_subplot(111, projection='3d') n = 100 for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:     xs = randrange(n, 23, 32)     ys = randrange(n, 0, 100)     zs = randrange(n, zl, zh)     cs = randrange(n, 0, 100)     ax.scatter(xs, ys, zs, c=cs, marker=m) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label')  plt.show() 

Will give a 3D scatter plot with different colors for each point (random colors in this example). What's the correct way to add a colorbar to the figure, since adding in plt.colorbar() or ax.colorbar() doesn't seem to work.

like image 779
JC. Avatar asked Mar 31 '11 04:03

JC.


People also ask

Can matplotlib plot 3D images?

Three-dimensional plotting is one of the functionalities that benefits immensely from viewing figures interactively rather than statically in the notebook; recall that to use interactive figures, you can use %matplotlib notebook rather than %matplotlib inline when running this code.


1 Answers

This produces a colorbar (though possibly not the one you need):

Replace this line:

ax.scatter(xs, ys, zs, c=cs, marker=m) 

with

p = ax.scatter(xs, ys, zs, c=cs, marker=m) 

then use

fig.colorbar(p) 

near the end

like image 118
marshall.ward Avatar answered Oct 11 '22 08:10

marshall.ward