From f4ce8fcff93e9c2feec281cd6bc8218a3d7a0141 Mon Sep 17 00:00:00 2001 From: Elias Carvalho <73039601+eliascarv@users.noreply.github.com> Date: Tue, 9 Apr 2024 19:54:28 -0300 Subject: [PATCH] Handle `Vector{Union{Missing,T}}` whitout missing values (#20) * Handle 'Vector{Union{Missing,T}}' whitout missing values * Add comments * Adjust function name * Rename variable --- src/Colorfy.jl | 34 ++++++++++++++++++++-------------- test/runtests.jl | 4 ++++ 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/Colorfy.jl b/src/Colorfy.jl index 3989d77..004f850 100644 --- a/src/Colorfy.jl +++ b/src/Colorfy.jl @@ -106,12 +106,11 @@ Default color alphas for `values`. defaultalphas(values::Values) = fill(1, length(values)) function defaultalphas(values::ValuesWithMissing) - vals = Vector{Float64}(undef, length(values)) minds = findall(ismissing, values) vinds = setdiff(1:length(values), minds) - vals[minds] .= 0.0 - vals[vinds] .= defaultalphas(coalesce.(values[vinds])) - vals + valphas = defaultalphas(nonmissingvec(values[vinds])) + malpha = zero(eltype(valphas)) + genvec(vinds, valphas, minds, malpha, length(values)) end defaultalphas(values::Values{Colorant}) = alpha.(values) @@ -143,19 +142,18 @@ function colors(colorfier::Colorfier) vinds = setdiff(1:length(vals), iinds) if isempty(iinds) - coloralpha.(getcolors(colorfier), alphas(colorfier)) + # required to handle Vector{Union{Missing,T}} without missing values + vvals = nonmissingvec(vals) + vcolorfier = update(colorfier, values=vvals) + coloralpha.(getcolors(vcolorfier), alphas(vcolorfier)) else - # invalid values are assigned full transparency - vcolors = Vector{Colorant}(undef, length(vals)) - vcolors[iinds] .= colorant"transparent" - - # set colors of valid values - vvals = coalesce.(vals[vinds]) + # get valid colors and set "transparent" for invalid values + vvals = nonmissingvec(vals[vinds]) valphas = alphas(colorfier)[vinds] vcolorfier = update(colorfier, values=vvals, alphas=valphas) - vcolors[vinds] .= colors(vcolorfier) - - vcolors + vcolors = colors(vcolorfier) + icolor = colorant"transparent" + genvec(vinds, vcolors, iinds, icolor, length(vals)) end end @@ -202,4 +200,12 @@ function asalphas(alphas::AbstractVector, values) alphas end +nonmissingvec(x::AbstractVector{T}) where {T} = convert(AbstractVector{nonmissingtype(T)}, x) + +function genvec(vecinds, vec, valinds, val, len) + valdict = Dict(i => val for i in valinds) + merge!(valdict, Dict(zip(vecinds, vec))) + [valdict[i] for i in 1:len] +end + end diff --git a/test/runtests.jl b/test/runtests.jl index 9c910b7..53cb8c4 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -91,6 +91,10 @@ using Test @test colors[4] == colorant"transparent" @test colors[6] == colorant"transparent" @test colors[8] == colorant"transparent" + + # Vector{Union{Missing,T}} whitout missing values + values = Union{Missing,Int}[1, 2, 3, 4, 5] + @test colorfy(values) == colorfy([1, 2, 3, 4, 5]) end @testset "Dates" begin