-
-
Notifications
You must be signed in to change notification settings - Fork 358
/
recipes.jl
1607 lines (1403 loc) · 46.6 KB
/
recipes.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const _series_recipe_deps = Dict()
series_recipe_dependencies(st::Symbol, deps::Symbol...) = _series_recipe_deps[st] = deps # COV_EXCL_LINE
seriestype_supported(st::Symbol) = seriestype_supported(backend(), st)
# returns :no, :native, or :recipe depending on how it's supported
function seriestype_supported(pkg::AbstractBackend, st::Symbol)
# is it natively supported
is_seriestype_supported(pkg, st) && return :native
haskey(_series_recipe_deps, st) || return :no
supported = true
for dep in _series_recipe_deps[st]
if seriestype_supported(pkg, dep) === :no
supported = false
break
end
end
supported ? :recipe : :no
end
macro deps(st, args...)
:(Plots.series_recipe_dependencies($(quot(st)), $(map(quot, args)...)))
end
# get a list of all seriestypes
function all_seriestypes()
sts = Set{Symbol}(keys(_series_recipe_deps))
for bsym in backends()
btype = _backendType[bsym]
sts = union(sts, Set{Symbol}(supported_seriestypes(btype())))
end
sts |> collect |> sort
end
# ----------------------------------------------------------------------------------
RecipesBase.apply_recipe(plotattributes::AKW, ::Type{T}, plt::AbstractPlot) where {T} =
nothing
# ---------------------------------------------------------------------------
# for seriestype `line`, need to sort by x values
const POTENTIAL_VECTOR_ARGUMENTS = [
:seriescolor,
:seriesalpha,
:linecolor,
:linealpha,
:linewidth,
:linestyle,
:line_z,
:fillcolor,
:fillalpha,
:fill_z,
:markercolor,
:markeralpha,
:markershape,
:marker_z,
:markerstrokecolor,
:markerstrokealpha,
:xerror,
:yerror,
:zerror,
:series_annotations,
:fillrange,
]
@nospecialize
@recipe function f(::Type{Val{:line}}, x, y, z) # COV_EXCL_LINE
indices = sortperm(x)
x := x[indices]
y := y[indices]
# sort vector arguments
for arg in POTENTIAL_VECTOR_ARGUMENTS
if typeof(plotattributes[arg]) <: AVec
plotattributes[arg] = _cycle(plotattributes[arg], indices)
end
end
# a tuple as fillrange has to be handled differently
if typeof(plotattributes[:fillrange]) <: Tuple
lower, upper = plotattributes[:fillrange]
typeof(lower) <: AVec && (lower = _cycle(lower, indices))
typeof(upper) <: AVec && (upper = _cycle(upper, indices))
plotattributes[:fillrange] = (lower, upper)
end
typeof(z) <: AVec && (z := z[indices])
seriestype := :path
()
end
@deps line path
@recipe function f(::Type{Val{:hline}}, x, y, z) # COV_EXCL_LINE
n = length(y)
newx = repeat(Float64[1, 2, NaN], n)
newy = vec(Float64[yi for i in 1:3, yi in y])
x := newx
y := newy
seriestype := :straightline
()
end
@deps hline straightline
@recipe function f(::Type{Val{:vline}}, x, y, z) # COV_EXCL_LINE
n = length(y)
newx = vec(Float64[yi for i in 1:3, yi in y])
x := newx
y := repeat(Float64[1, 2, NaN], n)
seriestype := :straightline
()
end
@deps vline straightline
@recipe function f(::Type{Val{:hspan}}, x, y, z) # COV_EXCL_LINE
n = div(length(y), 2)
newx = repeat([-Inf, Inf, Inf, -Inf, NaN], outer = n)
newy = vcat(map(i -> [y[2i - 1], y[2i - 1], y[2i], y[2i], NaN], 1:n)...)
linewidth --> 0
x := newx
y := newy
seriestype := :shape
()
end
@deps hspan shape
@recipe function f(::Type{Val{:vspan}}, x, y, z) # COV_EXCL_LINE
n = div(length(y), 2)
newx = vcat(map(i -> [y[2i - 1], y[2i - 1], y[2i], y[2i], NaN], 1:n)...)
newy = repeat([-Inf, Inf, Inf, -Inf, NaN], outer = n)
linewidth --> 0
x := newx
y := newy
seriestype := :shape
()
end
@deps vspan shape
# ---------------------------------------------------------------------------
# path and scatter
# create a path from steps
@recipe function f(::Type{Val{:scatterpath}}, x, y, z) # COV_EXCL_LINE
x := x
y := y
seriestype := :scatter
@series begin
()
end
@series begin
seriestype := :path
label := ""
primary := false
()
end
primary := false
()
end
@deps scatterpath path scatter
# ---------------------------------------------------------------------------
# regression line and scatter
# plots line corresponding to linear regression of y on a constant and x
@recipe function f(::Type{Val{:linearfit}}, x, y, z) # COV_EXCL_LINE
x := x
y := y
seriestype := :scatter
@series begin
()
end
@series begin
y := mean(y) .+ cov(x, y) / var(x) .* (x .- mean(x))
seriestype := :path
label := ""
primary := false
()
end
primary := false
()
end
@specialize
# ---------------------------------------------------------------------------
# steps
make_steps(x, st, even) = x
function make_steps(x::AbstractArray, st, even)
n = length(x)
n == 0 && return zeros(0)
newx = zeros(2n - (even ? 0 : 1))
newx[1] = x[1]
for i in 2:n
idx = 2i - 1
if st === :mid
newx[idx] = newx[idx - 1] = (x[i] + x[i - 1]) / 2
else
newx[idx] = x[i]
newx[idx - 1] = x[st === :pre ? i : i - 1]
end
end
even && (newx[end] = x[end])
return newx
end
make_steps(t::Tuple, st, even) = Tuple(make_steps(ti, st, even) for ti in t)
@nospecialize
# create a path from steps
@recipe function f(::Type{Val{:steppre}}, x, y, z) # COV_EXCL_LINE
plotattributes[:x] = make_steps(x, :post, false)
plotattributes[:y] = make_steps(y, :pre, false)
seriestype := :path
# handle fillrange
plotattributes[:fillrange] = make_steps(plotattributes[:fillrange], :pre, false)
# create a secondary series for the markers
if plotattributes[:markershape] !== :none
@series begin
seriestype := :scatter
x := x
y := y
label := ""
primary := false
()
end
markershape := :none
end
()
end
@deps steppre path scatter
# create a path from steps
@recipe function f(::Type{Val{:stepmid}}, x, y, z) # COV_EXCL_LINE
plotattributes[:x] = make_steps(x, :mid, true)
plotattributes[:y] = make_steps(y, :post, true)
seriestype := :path
# handle fillrange
plotattributes[:fillrange] = make_steps(plotattributes[:fillrange], :post, true)
# create a secondary series for the markers
if plotattributes[:markershape] !== :none
@series begin
seriestype := :scatter
x := x
y := y
label := ""
primary := false
()
end
markershape := :none
end
()
end
@deps stepmid path scatter
# create a path from steps
@recipe function f(::Type{Val{:steppost}}, x, y, z) # COV_EXCL_LINE
plotattributes[:x] = make_steps(x, :pre, false)
plotattributes[:y] = make_steps(y, :post, false)
seriestype := :path
# handle fillrange
plotattributes[:fillrange] = make_steps(plotattributes[:fillrange], :post, false)
# create a secondary series for the markers
if plotattributes[:markershape] !== :none
@series begin
seriestype := :scatter
x := x
y := y
label := ""
primary := false
()
end
markershape := :none
end
()
end
@deps steppost path scatter
# ---------------------------------------------------------------------------
# sticks
# create vertical line segments from fill
@recipe function f(::Type{Val{:sticks}}, x, y, z) # COV_EXCL_LINE
n = length(x)
if (fr = plotattributes[:fillrange]) === nothing
sp = plotattributes[:subplot]
fr = if sp[:yaxis][:scale] === :identity
0.0
else
NaNMath.min(axis_limits(sp, :y)[1], ignorenan_minimum(y))
end
end
newx, newy, newz = zeros(3n), zeros(3n), z !== nothing ? zeros(3n) : nothing
for (i, (xi, yi, zi)) in enumerate(zip(x, y, z !== nothing ? z : 1:n))
rng = (3i - 2):(3i)
newx[rng] = [xi, xi, NaN]
if z !== nothing
newy[rng] = [yi, yi, NaN]
newz[rng] = [_cycle(fr, i), zi, NaN]
else
newy[rng] = [_cycle(fr, i), yi, NaN]
end
end
x := newx
y := newy
if z !== nothing
z := newz
end
fillrange := nothing
seriestype := :path
if (
plotattributes[:linecolor] === :auto &&
plotattributes[:marker_z] !== nothing &&
plotattributes[:line_z] === nothing
)
line_z := plotattributes[:marker_z]
end
# create a primary series for the markers
if plotattributes[:markershape] !== :none
primary := false
@series begin
seriestype := :scatter
x := x
y := y
if z !== nothing
z := z
end
primary := true
()
end
markershape := :none
end
()
end
@deps sticks path scatter
@specialize
# ---------------------------------------------------------------------------
# bezier curves
# get the value of the curve point at position t
function bezier_value(pts::AVec, t::Real)
val = 0.0
n = length(pts) - 1
for (i, p) in enumerate(pts)
val += p * binomial(n, i - 1) * (1 - t)^(n - i + 1) * t^(i - 1)
end
val
end
@nospecialize
# create segmented bezier curves in place of line segments
@recipe function f(::Type{Val{:curves}}, x, y, z; npoints = 30) # COV_EXCL_LINE
args = z !== nothing ? (x, y, z) : (x, y)
newx, newy = zeros(0), zeros(0)
newfr = (fr = plotattributes[:fillrange]) !== nothing ? zeros(0) : nothing
newz = z !== nothing ? zeros(0) : nothing
# for each line segment (point series with no NaNs), convert it into a bezier curve
# where the points are the control points of the curve
for rng in iter_segments(args...)
length(rng) < 2 && continue
ts = range(0, stop = 1, length = npoints)
nanappend!(newx, map(t -> bezier_value(_cycle(x, rng), t), ts))
nanappend!(newy, map(t -> bezier_value(_cycle(y, rng), t), ts))
if z !== nothing
nanappend!(newz, map(t -> bezier_value(_cycle(z, rng), t), ts))
end
if fr !== nothing
nanappend!(newfr, map(t -> bezier_value(_cycle(fr, rng), t), ts))
end
end
x := newx
y := newy
if z === nothing
seriestype := :path
else
seriestype := :path3d
z := newz
end
if fr !== nothing
fillrange := newfr
end
()
end
@deps curves path
# ---------------------------------------------------------------------------
# create a bar plot as a filled step function
@recipe function f(::Type{Val{:bar}}, x, y, z) # COV_EXCL_LINE
ywiden --> false
procx, procy, xscale, yscale, _ = _preprocess_barlike(plotattributes, x, y)
nx, ny = length(procx), length(procy)
axis = plotattributes[:subplot][isvertical(plotattributes) ? :xaxis : :yaxis]
cv = map(xi -> discrete_value!(plotattributes, :x, xi)[1], procx)
procx = if nx == ny
cv
elseif nx == ny + 1
0.5diff(cv) + @view(cv[1:(end - 1)])
else
error(
"bar recipe: x must be same length as y (centers), or one more than y (edges).\n\t\tlength(x)=$(length(x)), length(y)=$(length(y))",
)
end
# compute half-width of bars
bw = plotattributes[:bar_width]
hw = if bw === nothing
0.5_bar_width * if nx > 1
ignorenan_minimum(filter(x -> x > 0, diff(sort(procx))))
else
1
end
else
map(i -> 0.5_cycle(bw, i), eachindex(procx))
end
# make fillto a vector... default fills to 0
if (fillto = plotattributes[:fillrange]) === nothing
fillto = 0
end
if yscale in _logScales && !all(_is_positive, fillto)
# github.com/JuliaPlots/Plots.jl/issues/4502
# https://github.com/JuliaPlots/Plots.jl/issues/4774
T = float(eltype(y))
min_y = NaNMath.minimum(y)
base = _logScaleBases[yscale]
baseline = floor_base(min_y, base)
if min_y == baseline
baseline /= base
end
fillto = map(x -> _is_positive(x) ? T(x) : T(baseline), fillto)
end
xseg, yseg = map(_ -> Segments(), 1:2)
valid_i = isfinite.(procx) .& isfinite.(procy)
for i in 1:ny
valid_i[i] || continue
yi = procy[i]
center = procx[i]
hwi = _cycle(hw, i)
fi = _cycle(fillto, i)
push!(xseg, center - hwi, center - hwi, center + hwi, center + hwi, center - hwi)
push!(yseg, yi, fi, fi, yi, yi)
end
# widen limits out a bit
expand_extrema!(axis, scale_lims(ignorenan_extrema(xseg.pts)..., default_widen_factor))
# switch back
if !isvertical(plotattributes)
xseg, yseg = yseg, xseg
x, y = y, x
end
# reset orientation
orientation := default(:orientation)
# draw the bar shapes
@series begin
seriestype := :shape
series_annotations := nothing
primary := true
x := xseg.pts
y := yseg.pts
# expand attributes to match indices in new series data
for k in _segmenting_vector_attributes ∪ _segmenting_array_attributes
if (v = get(plotattributes, k, nothing)) isa AVec
if eachindex(v) != eachindex(y)
@warn "Indices $(eachindex(v)) of attribute `$k` do not match data indices $(eachindex(y))."
end
# Each segment is 6 elements long, including the NaN separator.
# One segment is created for each non-NaN element of `procy`.
# There is no trailing NaN, so the last repetition is dropped.
plotattributes[k] = @views repeat(v[valid_i]; inner = 6)[1:(end - 1)]
end
end
()
end
# add empty series
primary := false
seriestype := :scatter
markersize := 0
markeralpha := 0
fillrange := nothing
x := procx
y := procy
()
end
@deps bar shape
# ---------------------------------------------------------------------------
# Plots Heatmap
@recipe function f(::Type{Val{:plots_heatmap}}, x, y, z) # COV_EXCL_LINE
xe, ye = heatmap_edges(x), heatmap_edges(y)
m, n = size(z.surf)
x_pts, y_pts = fill(NaN, 6m * n), fill(NaN, 6m * n)
fz = zeros(m * n)
for i in 1:m, j in 1:n # i ≡ y, j ≡ x
k = (j - 1) * m + i
inds = (6(k - 1) + 1):(6k - 1)
x_pts[inds] .= [xe[j], xe[j + 1], xe[j + 1], xe[j], xe[j]]
y_pts[inds] .= [ye[i], ye[i], ye[i + 1], ye[i + 1], ye[i]]
fz[k] = z.surf[i, j]
end
ensure_gradient!(plotattributes, :fillcolor, :fillalpha)
fill_z := fz
line_z := fz
x := x_pts
y := y_pts
z := nothing
seriestype := :shape
label := ""
widen --> false
()
end
@deps plots_heatmap shape
@specialize
is_3d(::Type{Val{:plots_heatmap}}) = true
RecipesPipeline.is_surface(::Type{Val{:plots_heatmap}}) = true
RecipesPipeline.is_surface(::Type{Val{:hexbin}}) = true
# ---------------------------------------------------------------------------
# Histograms
_bin_centers(v::AVec) = (@view(v[1:(end - 1)]) + @view(v[2:end])) / 2
_is_positive(x) = (x > 0) && !(x ≈ 0)
_positive_else_nan(::Type{T}, x::Real) where {T} = _is_positive(x) ? T(x) : T(NaN)
_scale_adjusted_values(
::Type{T},
V::AbstractVector,
scale::Symbol,
) where {T<:AbstractFloat} = scale in _logScales ? _positive_else_nan.(T, V) : T.(V)
_binbarlike_baseline(min_value::T, scale::Symbol) where {T<:Real} =
if scale in _logScales
isnan(min_value) ? T(1e-3) : floor_base(min_value, _logScaleBases[scale])
else
zero(T)
end
function _preprocess_binbarlike_weights(
::Type{T},
w,
wscale::Symbol,
) where {T<:AbstractFloat}
w_adj = _scale_adjusted_values(T, w, wscale)
w_min = ignorenan_minimum(w_adj)
w_max = ignorenan_maximum(w_adj)
baseline = _binbarlike_baseline(w_min, wscale)
w_adj, baseline
end
function _preprocess_barlike(plotattributes, x, y)
xscale = get(plotattributes, :xscale, :identity)
yscale = get(plotattributes, :yscale, :identity)
weights, baseline = _preprocess_binbarlike_weights(float(eltype(y)), y, yscale)
x, weights, xscale, yscale, baseline
end
function _preprocess_binlike(plotattributes, x, y)
xscale = get(plotattributes, :xscale, :identity)
yscale = get(plotattributes, :yscale, :identity)
T = float(promote_type(eltype(x), eltype(y)))
edge = T.(x)
weights, baseline = _preprocess_binbarlike_weights(T, y, yscale)
edge, weights, xscale, yscale, baseline
end
@nospecialize
@recipe function f(::Type{Val{:barbins}}, x, y, z) # COV_EXCL_LINE
edge, weights, xscale, yscale, baseline = _preprocess_binlike(plotattributes, x, y)
if plotattributes[:bar_width] === nothing
bar_width := diff(edge)
end
x := _bin_centers(edge)
y := weights
seriestype := :bar
()
end
@deps barbins bar
@recipe function f(::Type{Val{:scatterbins}}, x, y, z) # COV_EXCL_LINE
edge, weights, xscale, yscale, baseline = _preprocess_binlike(plotattributes, x, y)
@series begin
x := _bin_centers(edge)
xerror := diff(edge) / 2
primary := false
seriestype := :xerror
()
end
x := _bin_centers(edge)
y := weights
seriestype := :scatter
()
end
@deps scatterbins xerror scatter
@specialize
function _stepbins_path(edge, weights, baseline::Real, xscale::Symbol, yscale::Symbol)
log_scale_x = xscale in _logScales
log_scale_y = yscale in _logScales
nbins = length(eachindex(weights))
if length(eachindex(edge)) != nbins + 1
error("Edge vector must be 1 longer than weight vector")
end
x = eltype(edge)[]
y = eltype(weights)[]
it_tuple_e = iterate(edge)
a, it_state_e = it_tuple_e
it_tuple_e = iterate(edge, it_state_e)
it_tuple_w = iterate(weights)
last_w = eltype(weights)(NaN)
while it_tuple_e !== nothing && it_tuple_w !== nothing
b, it_state_e = it_tuple_e
w, it_state_w = it_tuple_w
if log_scale_x && a ≈ 0
a = oftype(a, b / _logScaleBases[xscale]^3)
end
if isnan(w)
if !isnan(last_w)
push!(x, a, NaN)
push!(y, baseline, NaN)
end
else
if isnan(last_w)
push!(x, a)
push!(y, baseline)
end
push!(x, a, b)
push!(y, w, w)
end
a = oftype(a, b)
last_w = oftype(last_w, w)
it_tuple_e = iterate(edge, it_state_e)
it_tuple_w = iterate(weights, it_state_w)
end
if (last_w != baseline)
push!(x, a)
push!(y, baseline)
end
(x, y)
end
@recipe function f(::Type{Val{:stepbins}}, x, y, z) # COV_EXCL_LINE
@nospecialize
axis = plotattributes[:subplot][Plots.isvertical(plotattributes) ? :xaxis : :yaxis]
edge, weights, xscale, yscale, baseline = _preprocess_binlike(plotattributes, x, y)
xpts, ypts = _stepbins_path(edge, weights, baseline, xscale, yscale)
if !isvertical(plotattributes)
xpts, ypts = ypts, xpts
end
# create a secondary series for the markers
if plotattributes[:markershape] !== :none
@series begin
seriestype := :scatter
x := _bin_centers(edge)
y := weights
fillrange := nothing
label := ""
primary := false
()
end
markershape := :none
xerror := :none
yerror := :none
end
x := xpts
y := ypts
seriestype := :path
()
end
@deps stepbins path
function wand_edges(x...)
@warn """"
Load the StatsPlots package in order to use :wand bins.
Defaulting to :auto
""" once = true
:auto
end
function _auto_binning_nbins(
vs::NTuple{N,AbstractVector},
dim::Integer;
mode::Symbol = :auto,
) where {N}
max_bins = 10_000
_cl(x) = min(ceil(Int, max(x, one(x))), max_bins)
_iqr(v) = (q = quantile(v, 0.75) - quantile(v, 0.25); q > 0 ? q : oftype(q, 1))
_span(v) = maximum(v) - minimum(v)
n_samples = length(LinearIndices(first(vs)))
# The nd estimator is the key to most automatic binning methods, and is modified for twodimensional histograms to include correlation
nd = n_samples^(1 / (2 + N))
nd = if N == 2
min(n_samples^(1 / (2 + N)), nd / (1 - cor(first(vs), last(vs))^2)^(3 // 8))
else # the >2-dimensional case does not have a nice solution to correlations
nd
end
v = vs[dim]
mode === :auto && (mode = :fd)
if mode === :sqrt # Square-root choice
_cl(sqrt(n_samples))
elseif mode === :sturges # Sturges' formula
_cl(log2(n_samples) + 1)
elseif mode === :rice # Rice Rule
_cl(2 * nd)
elseif mode === :scott # Scott's normal reference rule
_cl(_span(v) / (3.5 * std(v) / nd))
elseif mode === :fd # Freedman–Diaconis rule
_cl(_span(v) / (2 * _iqr(v) / nd))
elseif mode === :wand
wand_edges(v) # this makes this function not type stable, but the type instability does not propagate
else
error("Unknown auto-binning mode $mode")
end
end
_hist_edge(vs::NTuple{N,AbstractVector}, dim::Integer, binning::Integer) where {N} =
StatsBase.histrange(vs[dim], binning, :left)
_hist_edge(vs::NTuple{N,AbstractVector}, dim::Integer, binning::Symbol) where {N} =
_hist_edge(vs, dim, _auto_binning_nbins(vs, dim, mode = binning))
_hist_edge(vs::NTuple{N,AbstractVector}, dim::Integer, binning::AbstractVector) where {N} =
binning
_hist_edges(vs::NTuple{N,AbstractVector}, binning::NTuple{N,Any}) where {N} =
map(dim -> _hist_edge(vs, dim, binning[dim]), Tuple(1:N))
_hist_edges(
vs::NTuple{N,AbstractVector},
binning::Union{Integer,Symbol,AbstractVector},
) where {N} = map(dim -> _hist_edge(vs, dim, binning), Tuple(1:N))
_hist_norm_mode(mode::Symbol) = mode
_hist_norm_mode(mode::Bool) = mode ? :pdf : :none
_filternans(vs::NTuple{1,AbstractVector}) = filter!.(isfinite, vs)
function _filternans(vs::NTuple{N,AbstractVector}) where {N}
_invertedindex(v, not) = [j for (i, j) in enumerate(v) if !(i ∈ not)]
nots = union(Set.(findall.(!isfinite, vs))...)
_invertedindex.(vs, Ref(nots))
end
function _make_hist(
vs::NTuple{N,AbstractVector},
binning;
normed = false,
weights = nothing,
) where {N}
localvs = _filternans(vs)
edges = _hist_edges(localvs, binning)
h = float(
weights === nothing ?
StatsBase.fit(StatsBase.Histogram, localvs, edges, closed = :left) :
StatsBase.fit(
StatsBase.Histogram,
localvs,
StatsBase.Weights(weights),
edges,
closed = :left,
),
)
normalize!(h, mode = _hist_norm_mode(normed))
end
@nospecialize
@recipe function f(::Type{Val{:histogram}}, x, y, z) # COV_EXCL_LINE
seriestype := length(y) > 1e6 ? :stephist : :barhist
()
end
@deps histogram barhist
@recipe function f(::Type{Val{:barhist}}, x, y, z) # COV_EXCL_LINE
h = _make_hist(
tuple(y),
plotattributes[:bins],
normed = plotattributes[:normalize],
weights = plotattributes[:weights],
)
x := h.edges[1]
y := h.weights
seriestype := :barbins
()
end
@deps barhist barbins
@recipe function f(::Type{Val{:stephist}}, x, y, z) # COV_EXCL_LINE
h = _make_hist(
tuple(y),
plotattributes[:bins],
normed = plotattributes[:normalize],
weights = plotattributes[:weights],
)
x := h.edges[1]
y := h.weights
seriestype := :stepbins
()
end
@deps stephist stepbins
@recipe function f(::Type{Val{:scatterhist}}, x, y, z) # COV_EXCL_LINE
h = _make_hist(
tuple(y),
plotattributes[:bins],
normed = plotattributes[:normalize],
weights = plotattributes[:weights],
)
x := h.edges[1]
y := h.weights
seriestype := :scatterbins
()
end
@deps scatterhist scatterbins
@recipe function f(h::StatsBase.Histogram{T,1,E}) where {T,E} # COV_EXCL_LINE
seriestype --> :barbins
st_map = Dict(
:bar => :barbins,
:scatter => :scatterbins,
:step => :stepbins,
:steppost => :stepbins, # :step can be mapped to :steppost in pre-processing
)
seriestype := get(st_map, plotattributes[:seriestype], plotattributes[:seriestype])
if plotattributes[:seriestype] === :scatterbins
# Workaround, error bars currently not set correctly by scatterbins
edge, weights, xscale, yscale, baseline =
_preprocess_binlike(plotattributes, h.edges[1], h.weights)
xerror --> diff(h.edges[1]) / 2
seriestype := :scatter
(Plots._bin_centers(edge), weights)
else
(h.edges[1], h.weights)
end
end
@recipe f(hv::AbstractVector{H}) where {H<:StatsBase.Histogram} = # COV_EXCL_LINE
for h in hv
@series begin
h
end
end
# ---------------------------------------------------------------------------
# Histogram 2D
@recipe function f(::Type{Val{:bins2d}}, x, y, z) # COV_EXCL_LINE
edge_x, edge_y, weights = x, y, z.surf
float_weights = float(weights)
if !plotattributes[:show_empty_bins]
if float_weights === weights
float_weights = deepcopy(float_weights)
end
for (i, c) in enumerate(float_weights)
c == 0 && (float_weights[i] = NaN)
end
end
x := Plots._bin_centers(edge_x)
y := Plots._bin_centers(edge_y)
z := Surface(permutedims(float_weights))
seriestype := :heatmap
()
end
Plots.@deps bins2d heatmap
@recipe function f(::Type{Val{:histogram2d}}, x, y, z) # COV_EXCL_LINE
h = _make_hist(
(x, y),
plotattributes[:bins],
normed = plotattributes[:normalize],
weights = plotattributes[:weights],
)
x := h.edges[1]
y := h.edges[2]
z := Surface(h.weights)
seriestype := :bins2d
()
end
@deps histogram2d bins2d
@recipe function f(h::StatsBase.Histogram{T,2,E}) where {T,E} # COV_EXCL_LINE
seriestype --> :bins2d
(h.edges[1], h.edges[2], Surface(h.weights))
end
# ---------------------------------------------------------------------------
# pie
@recipe function f(::Type{Val{:pie}}, x, y, z) # COV_EXCL_LINE
framestyle --> :none
aspect_ratio --> 1
s = sum(y)
θ = 0
colors = plotattributes[:seriescolor]
for i in eachindex(y)
θ_new = θ + 2π * y[i] / s
coords = [(0.0, 0.0); partialcircle(θ, θ_new, 50)]
@series begin
seriescolor := _cycle(colors, i)
seriestype := :shape
label --> string(x[i])
x := first.(coords)
y := last.(coords)
end
θ = θ_new
end
end
@deps pie shape
# ---------------------------------------------------------------------------
# mesh 3d replacement for non-plotly backends
@recipe function f(::Type{Val{:mesh3d}}, x, y, z) # COV_EXCL_LINE
# As long as no i,j,k are supplied this should work with PyPlot and GR
seriestype := :surface
if plotattributes[:connections] !== nothing
"Giving triangles using the connections argument is only supported on Plotly backend." |>
ArgumentError |>
throw
end
()
end
# ---------------------------------------------------------------------------
# scatter 3d
@recipe function f(::Type{Val{:scatter3d}}, x, y, z) # COV_EXCL_LINE
seriestype := :path3d
if plotattributes[:markershape] === :none
markershape := :circle
end
linewidth := 0
linealpha := 0
()
end
# note: don't add dependencies because this really isn't a drop-in replacement
# ---------------------------------------------------------------------------
# lens! - magnify a region of a plot
lens!(args...; kwargs...) = plot!(args...; seriestype = :lens, kwargs...)
export lens!
@recipe function f(::Type{Val{:lens}}, plt::AbstractPlot) # COV_EXCL_LINE
sp_index, inset_bbox = plotattributes[:inset_subplots]
width(inset_bbox) isa Measures.Length{:w,<:Real} ||
throw(ArgumentError("Inset bounding box needs to in relative coordinates."))
sp = plt.subplots[sp_index]
xscale = sp[:xaxis][:scale]
yscale = sp[:yaxis][:scale]
xl1, xl2 = xlims(sp)
bbx1 = xl1 + left(inset_bbox).value * (xl2 - xl1)
bbx2 = bbx1 + width(inset_bbox).value * (xl2 - xl1)
yl1, yl2 = ylims(sp)
bby1 = yl1 + (1 - bottom(inset_bbox).value) * (yl2 - yl1)
bby2 = bby1 + height(inset_bbox).value * (yl2 - yl1)
bbx = bbx1 + width(inset_bbox).value * (xl2 - xl1) / 2 * (sp[:xaxis][:flip] ? -1 : 1)
bby = bby1 + height(inset_bbox).value * (yl2 - yl1) / 2 * (sp[:yaxis][:flip] ? -1 : 1)