Matplotlib:创建Colorbar

问题描述 投票:0回答:1

由于这个社区的大力帮助,我几乎达到了我的目标。我之前解释过我的目标: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)但它是emtpy(白色)。

python-3.x matplotlib 3d colorbar
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.