3

I'm currently conducting some 3D plots in Python 2.7.9 using Matplotlib 1.4.3. (Sorry, my rating does not allow me to attach pictures yet). I would like to switch the data of the x- and z-axes (as in the code example), but then also have the colorbar associate itself with the x-axis and not the z-axis anymore.

import pylab as py
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import matplotlib as mpl
from matplotlib import cm

# Create figure and get data
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)

# Plot surface and colorbar
c1 = ax.plot_surface(Z, Y, X, rstride=8, cstride=8, alpha=0.9, cmap='PiYG_r')
cbar = plt.colorbar(c1)

# Labels
ax.set_xlabel('X')
ax.set_xlim3d(-100, 100)
ax.set_ylabel('Y')
ax.set_ylim3d(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim3d(-40, 40)

plt.show()

When I switch the x- and z-axis data at this stage, the colorbar understandably also automatically changes to suit the new z-axis values (originally the x-axis values), since it is associated with the z-variable only. Is there a way of manipulating this in python to make the colorbar associate itself with one of the other axes (x- or y-axes)?

I've tried looking at the colorbar documentation. I currently suspect the config_axis() function might do the job, but there is no text explaining how it is used (http://matplotlib.org/api/colorbar_api.html).

Thanks in advance.

Regards

Francois

Francois
  • 33
  • 1
  • 6

1 Answers1

5

You have to use facecolors instead of cmap and for calling colorbar we have to create a mappable object using ScalarMappable. This code here worked for me.

import pylab as py
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import matplotlib as mpl
from matplotlib import cm

# Create figure and get data
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)

N = (Z-Z.min())/(Z-Z.min()).max()

# Plot surface and colorbar
c1 = ax.plot_surface(Z, Y, X, rstride=8, cstride=8, alpha=0.9, facecolors=cm.PiYG_r(N))

m = cm.ScalarMappable(cmap=cm.PiYG_r)
m.set_array(X)
cbar = plt.colorbar(m)


# Labels
ax.set_xlabel('X')
ax.set_xlim3d(-100, 100)
ax.set_ylabel('Y')
ax.set_ylim3d(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim3d(-40, 40)

plt.show()
plonser
  • 3,323
  • 2
  • 18
  • 22