如何使用Jupyter添加颜色条以在3D表面图中显示标量值

时间:2019-04-25 05:32:03

标签: matplotlib jupyter surface colorbar circuit

我一直试图通过Jupyter Notebook使用Matplotlib和Python3创建3D表面图,以可视化具有3个组件的电路的总电阻。我分别在x,y,z轴上具有分量1、2和3的电阻,并且我一直在尝试通过为表面分配颜色来可视化总电阻。我已经能够生成表面图并对其进行相应的着色,但是当我尝试在图上引入颜色条时,我遇到了很多错误。任何帮助添加颜色条和标签并据此进行缩放的帮助将不胜感激

import numpy as np
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib as mpl
import math
import matplotlib.pyplot as plt
import matplotlib.colors as colors
%matplotlib inline

from mpl_toolkits import mplot3d
from matplotlib import cm

fig = plt.figure(figsize=(15,15))
ax = fig.gca(projection='3d')

def f(r1,r2):
return (r1*r2)/(r1+r2)
r1 = np.linspace(0.001,15,100)
r2 = np.linspace(0.001,15,100)
X,Y = np.meshgrid(r1,r2)
W = f(X,Y)

def g(r12,r3):
return (r12*r3)/(r12+r3)
r12 = (r1*r2)/(r1+r2)
r3 = np.linspace(0.001,15,100)
A,B = np.meshgrid(r12,r3)
Z = g(A,B)

minn, maxx = Z.min(), Z.max()
norm = colors.LogNorm(minn,maxx)
m = plt.cm.ScalarMappable(norm=norm, cmap='coolwarm')
m.set_array([Z])
fcolors = cm.coolwarm(Z)

surf = ax.plot_surface(X,Y,B, rstride=1,cstride=1,
               facecolors=fcolors, vmin=minn,vmax=maxx, shade=False)
pcm = ax.pcolor(X,Y,B, data=Z, vmin=minn, vmax=minn, cmap= 'coolwarm')
plt.colorbar(pcm)

`with the pcm and plt.colorbar(pcm) lines hashed I am able to generate a 
coloured surface plot`

plt.title('Total Resistance Of Circuit with Three Components')
ax.set_xlabel('Component One Resistance')
ax.set_ylabel('Component Two Resistance')
ax.set_zlabel('Component Three Resistance')
plt.show()


`without the pcm and pltcolorbar(pcm) lines hashed I get the following 
error`


IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis 
(`None`) and integer or boolean arrays are valid indices


`I expect to see a 3d surface plot with a colorbar to the right of the 
plot where blue is for the lowest values and red for the highest values 
but instead my output is the surface plot with none of the labels when 
the pcm and plt lines are hashed`

1 个答案:

答案 0 :(得分:0)

根据this的答案及其下方的评论,以下是使其正常工作的一种方法

surf = ax.plot_surface(X,Y,B, rstride=1,cstride=1,
               facecolors=fcolors, vmin=minn,vmax=maxx, shade=False)
m = cm.ScalarMappable(cmap='coolwarm', norm=surf.norm)
m.set_array(B)
plt.colorbar(m)

enter image description here