Matplotlib 3D图-将颜色栏与不同的轴相关联 [英] Matplotlib 3d plot - associate colorbar with different axis

查看:55
本文介绍了Matplotlib 3D图-将颜色栏与不同的轴相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Matplotlib 1.4.3在Python 2.7.9中进行一些3D绘图.(很抱歉,我的评级还不能附加图片).我想切换x轴和z轴的数据(如代码示例中所示),但是还要使颜色条本身与x轴关联,而不再与z轴关联.

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

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

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

我尝试查看颜色栏文档.我目前怀疑config_axis()函数可以完成此工作,但是没有文字说明其用法( http://matplotlib.org/api/colorbar_api.html ).

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

谢谢.

致谢

Francois

推荐答案

您必须使用 facecolors 代替 cmap 并调用 colorbar 我们必须使用 ScalarMappable 创建一个可映射的对象.这段代码对我有用.

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

这篇关于Matplotlib 3D图-将颜色栏与不同的轴相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆