-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathUnitfulExt.jl
93 lines (83 loc) · 2.8 KB
/
UnitfulExt.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
module UnitfulExt
import UnicodePlots: UnicodePlots, KEYWORDS, Plot, Canvas, unitless
import Unitful: Quantity, RealOrRealQuantity, ustrip, unit
function unit_str(x, fancy)
io = IOContext(PipeBuffer(), :fancy_exponent => fancy)
show(io, unit(x))
read(io, String)
end
unit_label(label::AbstractString, unit::AbstractString) =
(lab_strip = rstrip(label)) |> isempty ? unit : "$lab_strip ($unit)"
unit_label(label::AbstractString, unit::Nothing) = rstrip(label)
number_unit(x::Union{AbstractVector,Number}, args...) = x, nothing
number_unit(x::AbstractVector{<:Quantity}, fancy = true) =
ustrip.(x), unit_str(first(x), fancy)
number_unit(x::Quantity, fancy = true) = ustrip(x), unit_str(x, fancy)
unitless(x::Quantity) = ustrip(x) # NOTE: keep in sync with src/common.jl
# ---------------------------------------------------------------------------- #
# lineplot
function UnicodePlots.lineplot(
x::AbstractVector{<:RealOrRealQuantity},
y::AbstractVector{<:RealOrRealQuantity};
unicode_exponent::Bool = KEYWORDS.unicode_exponent,
canvas::Type = KEYWORDS.canvas,
xlabel = KEYWORDS.xlabel,
ylabel = KEYWORDS.ylabel,
kw...,
)
pkw, okw = UnicodePlots.split_plot_kw(kw)
x, ux = number_unit(x, unicode_exponent)
y, uy = number_unit(y, unicode_exponent)
x_, y_ = unitless.(x), unitless.(y)
plot = Plot(
x_,
y_,
nothing,
canvas;
xlabel = unit_label(xlabel, ux),
ylabel = unit_label(ylabel, uy),
unicode_exponent,
pkw...,
)
UnicodePlots.lineplot!(plot, x_, y_; okw...)
end
UnicodePlots.lineplot!(
plot::Plot{<:Canvas},
x::AbstractVector{<:RealOrRealQuantity},
y::AbstractVector{<:Quantity};
kw...,
) = UnicodePlots.lineplot!(plot, unitless.(x), unitless.(y); kw...)
# ---------------------------------------------------------------------------- #
# scatterplot
function UnicodePlots.scatterplot(
x::AbstractVector{<:RealOrRealQuantity},
y::AbstractVector{<:RealOrRealQuantity};
unicode_exponent::Bool = KEYWORDS.unicode_exponent,
canvas::Type = KEYWORDS.canvas,
xlabel = KEYWORDS.xlabel,
ylabel = KEYWORDS.ylabel,
kw...,
)
pkw, okw = UnicodePlots.split_plot_kw(kw)
x, ux = number_unit(x, unicode_exponent)
y, uy = number_unit(y, unicode_exponent)
x_, y_ = unitless.(x), unitless.(y)
plot = Plot(
x_,
y_,
nothing,
canvas;
xlabel = unit_label(xlabel, ux),
ylabel = unit_label(ylabel, uy),
unicode_exponent,
pkw...,
)
UnicodePlots.scatterplot!(plot, x_, y_; okw...)
end
UnicodePlots.scatterplot!(
plot::Plot{<:Canvas},
x::AbstractVector{<:RealOrRealQuantity},
y::AbstractVector{<:Quantity};
kw...,
) = UnicodePlots.scatterplot!(plot, unitless.(x), unitless.(y); kw...)
end # module