Matplotlib:创建颜色栏

时间:2018-08-06 21:14:41

标签: python-3.x matplotlib 3d colorbar

由于这个社区的大力帮助,我几乎达到了目标。我之前在这里解释了我的目标:matplotlib: assign color to a radius

我现在有了我想要的情节。我的代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib import cm


ri = 100
ra = 300
h=20

# input xy coordinates
xy = np.array([[ri,0],[ra,0],[ra,h],[ri,h],[ri,0]])
# radial component is x values of input
r = xy[:,0]
# angular component is one revolution of 30 steps
phi = np.linspace(0, 2*np.pi, 50)
# create grid
R,Phi = np.meshgrid(r,phi)
# transform to cartesian coordinates
X = R*np.cos(Phi)
Y = R*np.sin(Phi)
# Z values are y values, repeated 30 times
Z = np.tile(xy[:,1],len(Y)).reshape(Y.shape)


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

ax.set_zlim(0,200)
ax.plot_surface(X, Y, Z, alpha=0.5, color='grey', rstride=1, cstride=1)

#here are the values which I want to visualize
arr = np.array([[ 114.28, 40],
                [ 128.57, 16],
                [ 142.85,19],
                [ 157.13,20],
                [ 171.41,21],
                [ 185.69,22],
                [ 199.97,24],
                [ 214.25,16],
                [ 228.53,29],
                [ 242.81,30],
                [ 257.09,31],
                [ 271.37,34],
                [ 288.65,35],
                [ 299.93,36],
                [ 300,38]])

#interpolating between the single values of the arrays
new_x = np.concatenate([np.linspace(arr[i,0],arr[i+1,0], num=20)
                        for i in range(len(arr)-1)])

new_y = np.interp(new_x, arr[:,0], arr[:,1])

#connecting new_x and new_y to one new array
arr = np.vstack((new_x, new_y)).T
a_min = min(arr[:,1])  # minimum level
a_max = max(arr[:,1])  # maximum level

# Levels rescaled to a range (0,1) using min and max levels as `15` and '22`. 
arr_norm = [(i - a_min)/(a_max - a_min) for i in arr[:,1]]

# Color scheme 'jet' mapped between `0` and `1`. 
colors = [cm.jet(i) for i in arr_norm]

# Plot circle with radius from `arr` and rescaled color between 0 and 1. 
for i, radius in enumerate(arr[:,0]):
p = Circle((0, 0), radius, fc='None', ec=colors[i])  
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=20, zdir="z")
plt.show()

我现在最后需要的是色条,其中代表哪种颜色代表哪个值,就像在轮廓图中所示: enter image description here 我已经尝试过colorbar(),但是要么有一个错误,什么都没发生,要么有一个范围为(0-> 1)的colorbar,但是它是空的(白色)。

1 个答案:

答案 0 :(得分:1)

这应该做到:

import matplotlib as mpl

cax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.8)
cbar = mpl.colorbar.ColorbarBase(cax, cmap='jet', label='some label',
                       norm=mpl.colors.Normalize(vmin=0., vmax=1.))

结果:

result