Skip to content

Commit

Permalink
Handle Vector{Union{Missing,T}} whitout missing values (#20)
Browse files Browse the repository at this point in the history
* Handle 'Vector{Union{Missing,T}}' whitout missing values

* Add comments

* Adjust function name

* Rename variable
  • Loading branch information
eliascarv authored Apr 9, 2024
1 parent db95340 commit f4ce8fc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/Colorfy.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit f4ce8fc

Please sign in to comment.