在热图中,我怎样才能创建一个三色渐变,蓝色表示负值,红色表示正值,白色表示零,这样如果有许多零值,大部分热图将是白色(而不是浅色)红色与默认渐变一样)。
A = [5 0 -3 -2 7; 0 5 0 0 0; -2 0 -1 0 0; -4 0 0 -10 0; 0 0 0 0 9]
using Plots
heatmap(Array(A),
c = cgrad([:blue,:white,:red]),
yflip = true,
xlabel = "row", ylabel = "col",
title = "Nonzeros, Positives, Negatives, in Matrix")
这里的渐变自动居中于中点,这是一个合理的默认设置。
相关:here。
后脚本
正如 BallPointBen 所建议的那样,计算值的范围似乎是推荐的方法。这是一些基准测试。 BallPointBen 建议的最佳方法是 max = maximum(abs, A)
julia> using BenchmarkTools
julia> A = rand(10_000, 10_100)
julia> @btime max = maximum(abs.(A))
432.837 ms (6 allocations: 770.57 MiB)
0.999999999929502
julia> @btime max = maximum(abs.(extrema(A)))
339.597 ms (5 allocations: 144 bytes)
0.999999999929502
julia> @btime max = maximum(abs, A)
60.690 ms (1 allocation: 16 bytes)
0.9999999985609005
答案 0 :(得分:2)
您可以计算数组中的最大绝对值,然后使用它来设置 clims
参数。比照http://docs.juliaplots.org/latest/generated/attributes_subplot/
julia> max_val = maximum(abs, A)
10
julia> heatmap(Array(A),
c = cgrad([:blue,:white,:red]),
yflip = true,
xlabel = "row", ylabel = "col",
title = "Nonzeros, Positives, Negatives, in Matrix",
clims=(-max_val, max_val))