Matplotlib 3d图 - 将颜色条与不同的轴相关联

时间:2015-02-19 06:34:20

标签: python matplotlib colorbar

我目前正在使用Matplotlib 1.4.3在Python 2.7.9中进行一些3D绘图。 (对不起,我的评分不允许我附上图片)。我想切换x轴和z轴的数据(如代码示例中所示),但也有颜色条本身与x轴而不是z轴相关联。

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()

当我在此阶段切换x轴和z轴数据时,颜色栏也可以理解地自动更改以适应新的z轴值(最初是x轴值),因为它与z变量相关联只要。有没有办法在python中操作它以使colorbar与其他轴(x轴或y轴)之一相关联?

我已经尝试过查看colorbar文档了。我目前怀疑config_axis()函数可能会完成这项工作,但是没有文字解释它是如何使用的(http://matplotlib.org/api/colorbar_api.html)。

提前致谢。

此致

弗朗索瓦

1 个答案:

答案 0 :(得分:5)

您必须使用facecolors代替cmap,并且要调用colorbar,我们必须使用ScalarMappable创建可映射对象。这段代码对我有用。

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()
相关问题