MatPlotlib 颜色条在 3D 表面中的范围错误

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

我试图使用 matplotlib 中的曲面图和面颜色在单位球体周围绘制一个值,但我的颜色条显示标准化值而不是真实值。我该如何解决这个问题以使颜色条具有正确的范围?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm

fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize = (10, 14))

# Make data
n_points = 500
r = 1
u = np.linspace(0, 2 * np.pi, n_points)
v = np.linspace(0, np.pi, n_points)
x = r * np.outer(np.cos(u), np.sin(v))
y = r * np.outer(np.sin(u), np.sin(v))
z = r * np.outer(np.ones(np.size(u)), np.cos(v))

ax.plot_wireframe(x, y, z, color="grey", alpha = 0.1)

data = np.random.uniform(0.2, 0.5, n_points)
heatmap = np.array(np.meshgrid(data, data))[1]

ax.set_aspect("equal")

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')


colormap = cm.viridis
normaliser = mpl.colors.Normalize(vmin=np.min(heatmap), vmax=np.max(heatmap))

print(np.min(heatmap))
print(np.max(heatmap))

surf = ax.plot_surface(
    x, y, z, 
    facecolors=colormap(normaliser(heatmap)), shade=False)
    

fig.colorbar(surf, shrink=0.5, aspect=10, label="Singlet yield", pad = 0.05, norm = normaliser)

plt.show()

这会输出

0.20009725794516225
0.49936395079063567
作为打印中的最小值和最大值,但您可以在下图中看到颜色条的范围是 0 到 1。 enter image description here

如何解决此问题并使颜色栏具有适当的颜色?

python matplotlib 3d
1个回答
0
投票
根据

该函数的文档

colorbar
函数本身没有
norm参数。为了最小化更改,您可以传递 matplotlib.cm.ScalarMappable
 作为 
colorbar
 调用的第一个参数,它会按预期工作(假设您还传递适当的 
ax
 参数)。

这是一个完全可运行的代码,演示了这一点:

import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import cm fig, ax = plt.subplots(subplot_kw={"projection": "3d"}, figsize=(10, 14)) # Make data n_points = 500 r = 1 u = np.linspace(0, 2 * np.pi, n_points) v = np.linspace(0, np.pi, n_points) x = r * np.outer(np.cos(u), np.sin(v)) y = r * np.outer(np.sin(u), np.sin(v)) z = r * np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_wireframe(x, y, z, color="grey", alpha=0.1) data = np.random.uniform(0.2, 0.5, n_points) heatmap = np.array(np.meshgrid(data, data))[1] ax.set_aspect("equal") ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') colormap = cm.viridis normaliser = mpl.colors.Normalize(vmin=np.min(heatmap), vmax=np.max(heatmap)) print(np.min(heatmap)) print(np.max(heatmap)) surf = ax.plot_surface( x, y, z, facecolors=colormap(normaliser(heatmap)), shade=False) mappable = cm.ScalarMappable(norm=normaliser, cmap=colormap) fig.colorbar(mappable, ax=ax, shrink=0.5, aspect=10, label="Singlet yield", pad=0.05) plt.show()
这是它生成的输出:

colourbar plot with correct bar extent

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