Julia Plots求助:cmap与clim不匹配,曲面颜色与色条不符
解决Julia中Plots曲面图颜色与色条不匹配的问题
问题描述
我在Julia中尝试绘制曲面图,期望曲面颜色与纵轴(π(ω,z)-c(x))值对应:负值为深红色,正值为深蓝色,值为0时为白色。能正常绘制图形,也能在plot函数中调整clim,但实际曲面颜色与右侧色条不匹配——clim仅改变色条,却不改变曲面颜色。例如纵轴值均为负值,但当纵轴值为-0.9时曲面仍呈白色,而色条显示正常。相关代码如下:
using Plots # Paramters A = 1 αω = 0.5 αz = 0.5 β1 = 1 β2 = 1 β0 = 0 γ = 1 # Functions π(ω,z) = A*ω^(αω)*z^(-αz) c(x) = β1*x + β2*x^2 + β0 p(x) = 1 - exp(-γ*x); F(x,Ω=Ω, Z=Z) = [π(ω_val, z_val) for ω_val in Ω, z_val in Z] .- [c(x) for ω_val in Ω, z_val in Z] # Grids Ω = range(0, 1, length=101) Z = range(0.4, 1, length=101) function plot_f(x, Ω=Ω, Z=Z) # Compute f(ω,z) = π(ω,z) - c(x) for each pair of ω and z values f_values = F(x,Ω,Z) # Compute the maximum absolute value of f_values max_abs = float(maximum(abs.(f_values))) # Create a 3D surface plot of f(ω,z) for the given value of x, with the colormap fixed at 0 for the white portion plot(Z,Ω,f_values,xlabel="z", ylabel="ω", zlabel="π(ω,z) - c($x)", st=:surface,camera=(30,30), cmap=:RdBu,clim=(-max_abs, max_abs), title="Current-period profit when x=$x") end plot_f(0.9)
解决方案
问题出在Plots.jl的surface绘图默认是根据z值的相对范围映射颜色,而非直接使用clim参数的绝对范围。要让曲面颜色和色条完全匹配,需要手动指定颜色映射的数据源为f_values,确保clim的范围正确应用到曲面颜色上。
修改后的代码:
using Plots # Parameters A = 1 αω = 0.5 αz = 0.5 β1 = 1 β2 = 1 β0 = 0 γ = 1 # Functions π(ω,z) = A*ω^(αω)*z^(-αz) c(x) = β1*x + β2*x^2 + β0 p(x) = 1 - exp(-γ*x); F(x,Ω=Ω, Z=Z) = [π(ω_val, z_val) for ω_val in Ω, z_val in Z] .- [c(x) for ω_val in Ω, z_val in Z] # Grids Ω = range(0, 1, length=101) Z = range(0.4, 1, length=101) function plot_f(x, Ω=Ω, Z=Z) # Compute f(ω,z) = π(ω,z) - c(x) for each pair of ω and z values f_values = F(x,Ω,Z) # Compute the maximum absolute value of f_values max_abs = float(maximum(abs.(f_values))) # Create a 3D surface plot, explicitly set color to f_values to align with clim plot(Z, Ω, f_values, xlabel="z", ylabel="ω", zlabel="π(ω,z) - c($x)", st=:surface, camera=(30,30), cmap=:RdBu, clim=(-max_abs, max_abs), color=f_values, # 关键:指定颜色映射的数据源为f_values title="Current-period profit when x=$x") end plot_f(0.9)
关键改动说明
- 在
plot函数中添加color=f_values参数,强制曲面的颜色直接使用f_values的值进行映射,而非默认的相对z轴范围。 - 保持
clim=(-max_abs, max_abs),确保色条和曲面颜色的映射范围一致,0值对应白色,负值偏向红色,正值偏向蓝色。
修改后,曲面颜色会严格按照f_values的绝对值和符号对应到色条上,解决颜色不匹配的问题。
内容的提问来源于stack exchange,提问作者Aaron Wolf
相关产品推荐
相关产品推荐

