-
Notifications
You must be signed in to change notification settings - Fork 250
/
statistics.jl
2345 lines (1958 loc) · 80.2 KB
/
statistics.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
module Stat
import Gadfly
import Contour
using Colors
using Compose
using DataStructures
using Dates
using Distributions
using Hexagons
using Loess
using CoupledFields # It is registered in METADATA.jl
using IndirectArrays
using Statistics
using LinearAlgebra
using Random
using Base.Iterators
import Gadfly: Scale, Coord, input_aesthetics, output_aesthetics,
default_scales, isconcrete, setfield!, discretize_make_ia, aes2str
import Compose: cyclezip
import KernelDensity
# import Distributions: Uniform, Distribution, qqbuild
include("bincount.jl")
function apply_statistics(stats::Vector{Gadfly.StatisticElement},
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
for stat in stats
apply_statistic(stat, scales, coord, aes)
end
nothing
end
struct Nil <: Gadfly.StatisticElement end
"""
Stat.Nil
"""
const nil = Nil
struct Identity <: Gadfly.StatisticElement end
apply_statistic(stat::Identity,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics) = nothing
"""
Stat.identity
"""
const identity = Identity
struct BandStatistic <: Gadfly.StatisticElement
orientation::Symbol # :horizontal or :vertical
end
function BandStatistic(; orientation=:vertical)
return BandStatistic(orientation)
end
input_aesthetics(stat::BandStatistic) = [:xmin, :xmax, :ymin, :ymax]
output_aesthetics(stat::BandStatistic) = [:xmin, :xmax, :ymin, :ymax]
default_scales(stat::BandStatistic) = [Scale.x_continuous(), Scale.y_continuous()]
"""
Stat.band[(; orientation=:vertical)]
Transform points in $(aes2str(input_aesthetics(band()))) into rectangles in
$(aes2str(output_aesthetics(band()))). Used by [`Geom.band`](@ref Gadfly.Geom.band).
"""
const band = BandStatistic
function apply_statistic(stat::BandStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
if stat.orientation == :horizontal
n = max(length(aes.ymin)) #Note: already passed check for equal lengths.
aes.xmin = fill(0w, n)
aes.xmax = fill(1w, n)
elseif stat.orientation == :vertical
n = max(length(aes.xmin)) #Note: already passed check for equal lengths.
aes.ymin = fill(0h, n)
aes.ymax = fill(1h, n)
else
error("Orientation must be :horizontal or :vertical")
end
end
# Determine bounds of bars positioned at the given values.
function barminmax(vals, iscontinuous::Bool)
minvalue, maxvalue = extrema(vals)
span_type = typeof((maxvalue - minvalue) / 1.0)
barspan = one(span_type)
if iscontinuous && length(vals) > 1
sorted_vals = sort(vals)
T = typeof(sorted_vals[2] - sorted_vals[1])
z = zero(T)
minspan = z
for i in 2:length(vals)
span = sorted_vals[i] - sorted_vals[i-1]
if span > z && (span < minspan || minspan == z)
minspan = span
end
end
barspan = minspan
end
position_type = promote_type(typeof(barspan/2.0), eltype(vals))
minvals = Array{position_type}(undef, length(vals))
maxvals = Array{position_type}(undef, length(vals))
for (i, x) in enumerate(vals)
minvals[i] = x - barspan/2.0
maxvals[i] = x + barspan/2.0
end
return minvals, maxvals
end
struct RectbinStatistic <: Gadfly.StatisticElement end
input_aesthetics(stat::RectbinStatistic) = [:x, :y]
output_aesthetics(stat::RectbinStatistic) = [:xmin, :xmax, :ymin, :ymax]
"""
Stat.rectbin
Transform $(aes2str(input_aesthetics(rectbin()))) into
$(aes2str(output_aesthetics(rectbin()))).
"""
const rectbin = RectbinStatistic
function apply_statistic(stat::RectbinStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
Gadfly.assert_aesthetics_defined("RectbinStatistic", aes, :x, :y)
isxcontinuous = haskey(scales, :x) && isa(scales[:x], Scale.ContinuousScale)
isycontinuous = haskey(scales, :y) && isa(scales[:y], Scale.ContinuousScale)
xminvals, xmaxvals = barminmax(aes.x, isxcontinuous)
yminvals, ymaxvals = barminmax(aes.y, isycontinuous)
aes.xmin = xminvals
aes.xmax = xmaxvals
aes.ymin = yminvals
aes.ymax = ymaxvals
if !isxcontinuous
aes.pad_categorical_x = false
end
if !isycontinuous
aes.pad_categorical_y = false
end
end
struct BarStatistic <: Gadfly.StatisticElement
position::Symbol # :dodge or :stack
orientation::Symbol # :horizontal or :vertical
end
BarStatistic(; position=:stack, orientation=:vertical) = BarStatistic(position, orientation)
input_aesthetics(stat::BarStatistic) = stat.orientation == :vertical ? [:x] : [:y]
output_aesthetics(stat::BarStatistic) =
stat.orientation == :vertical ? [:xmin, :xmax] : [:ymin, :ymax]
default_scales(stat::BarStatistic) = stat.orientation == :vertical ?
[Gadfly.Scale.y_continuous()] : [Gadfly.Scale.x_continuous()]
"""
Stat.bar[(; position=:stack, orientation=:vertical)]
Transform $(aes2str(input_aesthetics(bar()))) into
$(aes2str(output_aesthetics(bar()))). Used by [`Geom.bar`](@ref Gadfly.Geom.bar).
"""
const bar = BarStatistic
function apply_statistic(stat::BarStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
if stat.orientation == :horizontal
in(:x, Gadfly.defined_aesthetics(aes)) || return
var = :y
othervar = :x
minvar = :ymin
maxvar = :ymax
viewminvar = :xviewmin
viewmaxvar = :xviewmax
other_viewminvar = :yviewmin
other_viewmaxvar = :yviewmax
labelvar = :x_label
else
in(:y, Gadfly.defined_aesthetics(aes)) || return
var = :x
othervar = :y
minvar = :xmin
maxvar = :xmax
viewminvar = :yviewmin
viewmaxvar = :yviewmax
other_viewminvar = :xviewmin
other_viewmaxvar = :xviewmax
labelvar = :y_label
end
vals = getfield(aes, var)
vals===nothing && (vals = getfield(aes, minvar))
if vals===nothing || isempty(vals)
setfield!(aes, minvar, Float64[1.0])
setfield!(aes, maxvar, Float64[1.0])
setfield!(aes, var, Float64[1.0])
setfield!(aes, othervar, Float64[0.0])
return
end
iscontinuous = haskey(scales, var) && isa(scales[var], Scale.ContinuousScale)
if getfield(aes, minvar) == nothing || getfield(aes, maxvar) == nothing
minvals, maxvals = barminmax(vals, iscontinuous)
setfield!(aes, minvar, minvals)
setfield!(aes, maxvar, maxvals)
end
z = zero(eltype(getfield(aes, othervar)))
if getfield(aes, viewminvar) == nothing && z < minimum(getfield(aes, othervar))
setfield!(aes, viewminvar, z)
elseif getfield(aes, viewmaxvar) == nothing && z > maximum(getfield(aes, othervar))
setfield!(aes, viewmaxvar, z)
end
if stat.position == :stack && aes.color !== nothing
groups = Dict{Any,Float64}()
for (x, y) in zip(getfield(aes, othervar), vals)
Gadfly.isconcrete(x) || continue
if !haskey(groups, y)
groups[y] = Float64(x)
else
groups[y] += Float64(x)
end
end
viewmin, viewmax = extrema(values(groups))
aes_viewminvar = getfield(aes, viewminvar)
if aes_viewminvar === nothing || aes_viewminvar > viewmin
setfield!(aes, viewminvar, viewmin)
end
aes_viewmaxvar = getfield(aes, viewmaxvar)
if aes_viewmaxvar === nothing || aes_viewmaxvar < viewmax
setfield!(aes, viewmaxvar, viewmax)
end
end
if !iscontinuous
if stat.orientation == :horizontal
aes.pad_categorical_y = false
else
aes.pad_categorical_x = false
end
end
end
struct HistogramStatistic <: Gadfly.StatisticElement
minbincount::Int
maxbincount::Int
position::Symbol # :dodge or :stack
orientation::Symbol
density::Bool
limits::NamedTuple
end
function HistogramStatistic(; bincount=nothing,
minbincount=3,
maxbincount=150,
position=:stack,
orientation=:vertical,
density=false,
limits=NamedTuple())
if bincount != nothing
HistogramStatistic(bincount, bincount, position, orientation, density, limits)
else
HistogramStatistic(minbincount, maxbincount, position, orientation, density, limits)
end
end
input_aesthetics(stat::HistogramStatistic) = stat.orientation == :vertical ? [:x] : [:y] ### and :color
output_aesthetics(stat::HistogramStatistic) =
stat.orientation == :vertical ? [:x, :y, :xmin, :xmax] : [:y, :x, :ymin, :ymax]
default_scales(stat::HistogramStatistic) = stat.orientation == :vertical ?
[Gadfly.Scale.y_continuous()] : [Gadfly.Scale.x_continuous()]
"""
Stat.histogram[(; bincount=nothing, minbincount=3, maxbincount=150,
position=:stack, orientation=:vertical, density=false, limits=NamedTuple())]
Transform $(aes2str(input_aesthetics(histogram()))) into
$(aes2str(output_aesthetics(histogram()))), optionally grouping by `color`.
Exchange y for x when `orientation` is `:horizontal`. `bincount` specifies the
number of bins to use. If set to `nothing`, an optimization method is used to
determine a reasonable value which uses `minbincount` and `maxbincount` to set
the lower and upper limits. If `density` is `true`, normalize the counts by
their total. `limits` is a `NamedTuple` that sets the limits of the histogram `(min= , max= )`:
`min` or `max` or both can be set.
"""
const histogram = HistogramStatistic
function apply_statistic(stat::HistogramStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
if stat.orientation == :horizontal
var = :y
othervar = :x
minvar = :ymin
maxvar = :ymax
viewminvar = :xviewmin
viewmaxvar = :xviewmax
labelvar = :x_label
else
var = :x
othervar = :y
minvar = :xmin
maxvar = :xmax
viewminvar = :yviewmin
viewmaxvar = :yviewmax
labelvar = :y_label
end
Gadfly.assert_aesthetics_defined("HistogramStatistic", aes, var)
vals = getfield(aes, var)
stat.minbincount > stat.maxbincount && error("Histogram minbincount > maxbincount")
if isempty(getfield(aes, var))
setfield!(aes, minvar, Float64[1.0])
setfield!(aes, maxvar, Float64[1.0])
setfield!(aes, var, Float64[1.0])
setfield!(aes, othervar, Float64[0.0])
return
end
if haskey(scales, var) && isa(scales[var], Scale.DiscreteScale)
isdiscrete = true
x_min, x_max = extrema(vals)
d = x_max - x_min + 1
bincounts = zeros(Int, d)
for x in vals
bincounts[x - x_min + 1] += 1
end
x_min -= 0.5 # adjust the left side of the bar
binwidth = 1.0
else
lims = keys(stat.limits)
x_min = in(:min, lims) ? stat.limits.min : Gadfly.concrete_minimum(vals)
isdiscrete = false
if estimate_distinct_proportion(vals) <= 0.9
value_set = sort!(collect(Set(vals[Bool[Gadfly.isconcrete(v) for v in vals]])))
d, bincounts, xmax = choose_bin_count_1d_discrete(vals, value_set, stat.minbincount, stat.maxbincount)
else
d, bincounts, xmax = choose_bin_count_1d(vals, stat.minbincount, stat.maxbincount)
end
x_max = in(:max, lims) ? stat.limits.max : xmax
binwidth = (x_max - x_min) / d
end
stat.density && (bincounts = bincounts ./ (sum(bincounts) * binwidth))
if aes.color === nothing
T = typeof(x_min + 1*binwidth)
setfield!(aes, othervar, Array{Float64}(undef, d))
setfield!(aes, minvar, Array{T}(undef, d))
setfield!(aes, maxvar, Array{T}(undef, d))
setfield!(aes, var, Array{T}(undef, d))
for j in 1:d
getfield(aes, minvar)[j] = x_min + (j - 1) * binwidth
getfield(aes, maxvar)[j] = x_min + j * binwidth
getfield(aes, var)[j] = x_min + (j - 0.5) * binwidth
getfield(aes, othervar)[j] = bincounts[j]
end
else
CT, VT = eltype(aes.color), eltype(vals)
groups = Dict{CT,Vector{VT}}(c=>VT[] for c in unique(aes.color))
for (x, c) in zip(vals, cycle(aes.color))
Gadfly.isconcrete(x) && push!(groups[c], x)
end
T = typeof(x_min + 1*binwidth)
setfield!(aes, minvar, Array{T}(undef, d * length(groups)))
setfield!(aes, maxvar, Array{T}(undef, d * length(groups)))
setfield!(aes, var, Array{T}(undef, d * length(groups)))
setfield!(aes, othervar, Array{Float64}(undef, d * length(groups)))
colors = Array{RGB{Float32}}(undef, d * length(groups))
x_span = x_max - x_min
stack_height = zeros(Int, d)
for (i, c) in enumerate(unique(aes.color))
xs = groups[c]
fill!(bincounts, 0)
for x in xs
if isdiscrete
bincounts[round(Int,x)] += 1
else
bin = max(1, min(d, (ceil(Int, (x - x_min) / binwidth))))
bincounts[bin] += 1
end
end
if stat.density
binwidth = x_span / d
bincounts = bincounts ./ (sum(bincounts) * binwidth)
end
stack_height += bincounts[1:d]
for j in 1:d
idx = (i-1)*d + j
getfield(aes, var)[idx] = isdiscrete ? j : x_min + (j - 0.5) * binwidth
getfield(aes, minvar)[idx] = x_min + (j - 1) * binwidth
getfield(aes, maxvar)[idx] = x_min + j * binwidth
getfield(aes, othervar)[idx] = bincounts[j]
colors[idx] = c
end
end
if stat.position == :stack
viewmax = Float64(maximum(stack_height))
aes_viewmax = getfield(aes, viewmaxvar)
if aes_viewmax === nothing || aes_viewmax < viewmax
setfield!(aes, viewmaxvar, viewmax)
end
end
aes.color = discretize_make_ia(colors)
end
getfield(aes, viewminvar) === nothing && setfield!(aes, viewminvar, 0.0)
if haskey(scales, othervar)
data = Gadfly.Data()
setfield!(data, othervar, getfield(aes, othervar))
setfield!(data, viewmaxvar, getfield(aes, viewmaxvar))
Scale.apply_scale(scales[othervar], [aes], data)
# See issue #560. Stacked histograms on a non-linear y scale are a strange
# thing. After some discussion, the least confusing thing is to make the stack
# partitioned linearly. Here we make that adjustment.
if stat.position == :stack && aes.color != nothing
# A little trickery to figure out the scale stack height.
data = Gadfly.Data()
setfield!(data, othervar, stack_height)
scaled_stackheight_aes = Gadfly.Aesthetics()
Scale.apply_scale(scales[othervar], [scaled_stackheight_aes], data)
scaled_stackheight = getfield(scaled_stackheight_aes, othervar)
othervals = getfield(aes, othervar)
for j in 1:d
naive_stackheight = 0
for i in 1:length(groups)
idx = (i-1)*d + j
naive_stackheight += othervals[idx]
end
naive_stackheight == 0 && continue
for i in 1:length(groups)
idx = (i-1)*d + j
othervals[idx] = scaled_stackheight[j] * othervals[idx] / naive_stackheight
end
end
end
else
setfield!(aes, labelvar, Scale.identity_formatter)
end
end
struct Density2DStatistic <: Gadfly.StatisticElement
n::Tuple{Int,Int} # Number of points sampled
bw::Tuple{Real,Real} # Bandwidth used for the kernel density estimation
levels::Union{Int,Vector,Function}
end
Density2DStatistic(; n=(256,256), bandwidth=(-Inf,-Inf), levels=15) =
Density2DStatistic(n, bandwidth, levels)
input_aesthetics(stat::Density2DStatistic) = [:x, :y]
output_aesthetics(stat::Density2DStatistic) = [:x, :y, :z]
default_scales(::Density2DStatistic) = [Gadfly.Scale.y_continuous()]
"""
Stat.density2d[(; n=(256,256), bandwidth=(-Inf,-Inf), levels=15)]
Estimate the density of $(aes2str(input_aesthetics(density2d()))) at `n` points
and put the results into $(aes2str(output_aesthetics(density2d()))). Smoothing
is controlled by `bandwidth`. Calls [`Stat.contour`](@ref) to compute the
`levels`. Used by [`Geom.density2d`](@ref Gadfly.Geom.density2d).
"""
const density2d = Density2DStatistic
function apply_statistic(stat::Density2DStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
window = (stat.bw[1] <= 0.0 ? KernelDensity.default_bandwidth(aes.x) : stat.bw[1],
stat.bw[2] <= 0.0 ? KernelDensity.default_bandwidth(aes.y) : stat.bw[2])
Dat = [aes.x aes.y]
linestyleflag = aes.linestyle ≠ nothing
colorflag = aes.color ≠ nothing
aes_color = colorflag ? aes.color : [nothing]
aes_group = (aes.group ≠ nothing) ? aes.group : [nothing]
CT, GT = eltype(aes_color), eltype(aes_group)
groups = collect(Tuple{CT, GT}, Compose.cyclezip(aes_color, aes_group))
ugroups = unique(groups)
nugroups = length(ugroups)
K, V = Tuple{CT, GT}, Matrix{eltype(Dat)}
grouped_xy = if nugroups==1
Dict{K, V}(ugroups[1]=>Dat)
elseif nugroups>1
Dict{K, V}(g=>Dat[groups.==[g],:] for g in ugroups)
end
aess = Gadfly.Aesthetics[]
for (g, data) in grouped_xy
aes1 = Gadfly.Aesthetics()
k = KernelDensity.kde(data, bandwidth=window, npoints=stat.n)
aes1.x, aes1.y, aes1.z = k.x, k.y, k.density
apply_statistic(ContourStatistic(levels=stat.levels), scales, coord, aes1)
colorflag && (aes1.color = fill(g[1], length(aes1.x)))
push!(aess, aes1)
end
aes2 = Gadfly.concat(aess...)
aes.x, aes.y, aes.color = aes2.x, aes2.y, aes2.color
colorflag && (linestyleflag ? (aes.group = aes2.group) : (aes.linestyle = aes2.group.+1))
if !colorflag
aes.group = aes2.group
aes.color_function = aes2.color_function
aes.color_label = aes2.color_label
aes.color_key_colors = aes2.color_key_colors
aes.color_key_continuous = aes2.color_key_continuous
end
end
struct DensityStatistic <: Gadfly.StatisticElement
# Number of points sampled
n::Int
# Bandwidth used for the kernel density estimation
bw::Real
end
DensityStatistic(; n=256, bandwidth=-Inf) = DensityStatistic(n, bandwidth)
input_aesthetics(stat::DensityStatistic) = [:x, :color]
output_aesthetics(stat::DensityStatistic) = [:x, :y, :color]
default_scales(::DensityStatistic) = [Gadfly.Scale.y_continuous()]
"""
Stat.density[(; n=256, bandwidth=-Inf)]
Estimate the density of `x` at `n` points, and put the result in `x` and `y`.
Smoothing is controlled by `bandwidth`. Used by [`Geom.density`](@ref Gadfly.Geom.density).
"""
const density = DensityStatistic
function apply_statistic(stat::DensityStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
Gadfly.assert_aesthetics_defined("DensityStatistic", aes, :x)
if aes.color === nothing
isa(aes.x[1], Real) || error("Kernel density estimation only works on Real types.")
x_f64 = collect(Float64, aes.x)
window = stat.bw <= 0.0 ? KernelDensity.default_bandwidth(x_f64) : stat.bw
f = KernelDensity.kde(x_f64, bandwidth=window, npoints=stat.n)
aes.x = collect(Float64, f.x)
aes.y = f.density
else
groups = Dict()
for (x, c) in zip(aes.x, cycle(aes.color))
if !haskey(groups, c)
groups[c] = Float64[x]
else
push!(groups[c], x)
end
end
colors = Array{RGB{Float32}}(undef, 0)
aes.x = Array{Float64}(undef, 0)
aes.y = Array{Float64}(undef, 0)
for (c, xs) in groups
window = stat.bw <= 0.0 ? KernelDensity.default_bandwidth(xs) : stat.bw
f = KernelDensity.kde(xs, bandwidth=window, npoints=stat.n)
append!(aes.x, f.x)
append!(aes.y, f.density)
for _ in 1:length(f.x)
push!(colors, c)
end
end
aes.color = discretize_make_ia(colors)
end
aes.y_label = Gadfly.Scale.identity_formatter
end
struct Histogram2DStatistic <: Gadfly.StatisticElement
xminbincount::Int
xmaxbincount::Int
yminbincount::Int
ymaxbincount::Int
end
function Histogram2DStatistic(; xbincount=nothing,
xminbincount=3,
xmaxbincount=150,
ybincount=nothing,
yminbincount=3,
ymaxbincount=150)
if xbincount != nothing
xminbincount = xbincount
xmaxbincount = xbincount
end
if ybincount != nothing
yminbincount = ybincount
ymaxbincount = ybincount
end
Histogram2DStatistic(xminbincount, xmaxbincount, yminbincount, ymaxbincount)
end
input_aesthetics(stat::Histogram2DStatistic) = [:x, :y]
output_aesthetics(stat::Histogram2DStatistic) = [:xmin, :ymax, :ymin, :ymax, :color]
default_scales(::Histogram2DStatistic, t::Gadfly.Theme=Gadfly.current_theme()) =
[t.continuous_color_scale]
"""
Stat.histogram2d[(; xbincount=nothing, xminbincount=3, xmaxbincount=150,
ybincount=nothing, yminbincount=3, ymaxbincount=150)]
Bin the points in $(aes2str(input_aesthetics(histogram2d()))) into rectangles
in $(aes2str(output_aesthetics(histogram2d()))). `xbincount` and `ybincount`
manually fix the number of bins. If set to `nothing`, an optimization method
is used to determine a reasonable value which uses `xminbincount`,
`xmaxbincount`, `yminbincount` and `ymaxbincount` to set the lower and upper
limits.
"""
const histogram2d = Histogram2DStatistic
function apply_statistic(stat::Histogram2DStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
Gadfly.assert_aesthetics_defined("Histogram2DStatistic", aes, :x, :y)
x_min, x_max = Gadfly.concrete_minimum(aes.x), Gadfly.concrete_maximum(aes.x)
y_min, y_max = Gadfly.concrete_minimum(aes.y), Gadfly.concrete_maximum(aes.y)
if haskey(scales, :x) && isa(scales[:x], Scale.DiscreteScale)
x_categorial = true
xminbincount = x_max - x_min + 1
xmaxbincount = xminbincount
else
x_categorial = false
xminbincount = stat.xminbincount
xmaxbincount = stat.xmaxbincount
end
if haskey(scales, :y) && isa(scales[:y], Scale.DiscreteScale)
y_categorial = true
yminbincount = y_max - y_min + 1
ymaxbincount = yminbincount
else
y_categorial = false
yminbincount = stat.yminbincount
ymaxbincount = stat.ymaxbincount
end
dy, dx, bincounts = choose_bin_count_2d(aes.x, aes.y,
xminbincount, xmaxbincount,
yminbincount, ymaxbincount)
wx = (x_max==x_min) ? 1.0 : (x_max - x_min) / dx
wy = (y_max==y_min) ? 1.0 : (y_max - y_min) / dy
!x_categorial && (x_max==x_min) && (x_min-=0.5)
!y_categorial && (y_max==y_min) && (y_min-=0.5)
n = 0
for cnt in bincounts
if cnt > 0
n += 1
end
end
if x_categorial
aes.x = Array{Int64}(undef, n)
else
aes.xmin = Array{Float64}(undef, n)
aes.xmax = Array{Float64}(undef, n)
end
if y_categorial
aes.y = Array{Int64}(undef, n)
else
aes.ymin = Array{Float64}(undef, n)
aes.ymax = Array{Float64}(undef, n)
end
k = 1
for i in 1:dy, j in 1:dx
cnt = bincounts[i, j]
if cnt > 0
if x_categorial
aes.x[k] = x_min + (j - 1)
else
aes.xmin[k] = x_min + (j - 1) * wx
aes.xmax[k] = x_min + j * wx
end
if y_categorial
aes.y[k] = y_min + (i - 1)
else
aes.ymin[k] = y_min + (i - 1) * wy
aes.ymax[k] = y_min + i * wy
end
k += 1
end
end
@assert k - 1 == n
haskey(scales, :color) || error("Histogram2DStatistic requires a color scale.")
color_scale = scales[:color]
typeof(color_scale) <: Scale.ContinuousColorScale ||
error("Histogram2DStatistic requires a continuous color scale.")
aes.color_key_title = "Count"
data = Gadfly.Data()
data.color = Array{Int}(undef, n)
k = 1
for cnt in transpose(bincounts)
if cnt > 0
data.color[k] = cnt
k += 1
end
end
if x_categorial
aes.xmin, aes.xmax = barminmax(aes.x, false)
aes.x = discretize_make_ia(aes.x)
aes.pad_categorical_x = false
end
if y_categorial
aes.ymin, aes.ymax = barminmax(aes.y, false)
aes.y = discretize_make_ia(aes.y)
aes.pad_categorical_y = false
end
Scale.apply_scale(color_scale, [aes], data)
nothing
end
# Find reasonable places to put tick marks and grid lines.
struct TickStatistic <: Gadfly.StatisticElement
axis::AbstractString
granularity_weight::Float64
simplicity_weight::Float64
coverage_weight::Float64
niceness_weight::Float64
# fixed ticks, or nothing
ticks::Union{Symbol, AbstractArray}
end
@deprecate xticks(ticks) xticks(ticks=ticks)
### add hinges and fences to y-axis?
input_aesthetics(stat::TickStatistic) = stat.axis=="x" ? [:x, :xmin, :xmax, :xintercept, :xend] :
[:y, :ymin, :ymax, :yintercept, :middle, :lower_hinge, :upper_hinge, :lower_fence, :upper_fence, :yend]
output_aesthetics(stat::TickStatistic) = stat.axis=="x" ? [:xtick, :xgrid] : [:ytick, :ygrid]
xy_ticks(var,in_aess,out_aess) = """
Stat.$(var)ticks[(; ticks=:auto, granularity_weight=1/4, simplicity_weight=1/6,
coverage_weight=1/3, niceness_weight=1/4)]
Compute an appealing set of $(var)-ticks that encompass the data by
transforming $(in_aess) into $(out_aess). `ticks` is a vector of desired
values, or `:auto` to indicate they should be computed. the importance of
having a reasonable number of ticks is specified with `granularity_weight`; of
including zero with `simplicity_weight`; of tightly fitting the span of the
data with `coverage_weight`; and of having a nice numbering with
`niceness_weight`.
"""
# can be put on two lines with julia 0.7
@doc xy_ticks("x",aes2str(input_aesthetics(xticks())), aes2str(output_aesthetics(xticks()))) xticks(; ticks=:auto,
granularity_weight=1/4,
simplicity_weight=1/6,
coverage_weight=1/3,
niceness_weight=1/4) =
TickStatistic("x",
granularity_weight, simplicity_weight, coverage_weight, niceness_weight, ticks)
@deprecate yticks(ticks) yticks(ticks=ticks)
@doc xy_ticks("y",aes2str(input_aesthetics(yticks())), aes2str(output_aesthetics(yticks()))) yticks(; ticks=:auto,
granularity_weight=1/4,
simplicity_weight=1/6,
coverage_weight=1/3,
niceness_weight=1/4) =
TickStatistic("y",
granularity_weight, simplicity_weight, coverage_weight, niceness_weight, ticks)
function apply_statistic(stat::TickStatistic,
scales::Dict{Symbol, Gadfly.ScaleElement},
coord::Gadfly.CoordinateElement,
aes::Gadfly.Aesthetics)
in_vars = input_aesthetics(stat)
isa(stat.ticks, Symbol) && stat.ticks != :auto &&
error("Invalid value $(stat.ticks) for ticks parameter.")
isa(coord, Coord.SubplotGrid) &&
error("TickStatistic cannot be applied to subplot coordinates.")
# don't clobber existing ticks
getfield(aes, Symbol(stat.axis, "tick")) == nothing || return
in_group_var = Symbol(stat.axis, "group")
minval, maxval = missing, missing
in_vals = Any[]
categorical = (:x in in_vars && Scale.iscategorical(scales, :x)) ||
(:y in in_vars && Scale.iscategorical(scales, :y))
dsize = nothing
stat.axis == "x" && (dsize = aes.xsize)
stat.axis == "y" && (dsize = aes.ysize)
size = aes.size
sizeflag = aes.size ≠ nothing && !(eltype(aes.size)<:Measure)
for var in in_vars
categorical && !in(var,[:x,:y]) && continue
vals = getfield(aes, var)
if vals≠nothing && !isempty(vals) && eltype(vals)≠Function
vv = [vals; minval; maxval]
if in(var, [:x, :y])
sizeflag && (vv = vec([x+s*d for (x, d) in cyclezip(vals, size), s in [-1.0, 1.0]]))
dsize≠nothing && (vv= vcat(vv, vec([x+s*d for (x, d) in cyclezip(vals, dsize), s in [-1.0, 1.0]])))
end
isc = Gadfly.isconcrete.(vv)
minval, maxval = if isa(vv, Vector{Any})
isntM = [!(typeof(v) <: Measure) for v in vv]
extrema(vv[isntM .& isc])
else
extrema(vv[isc])
end
push!(in_vals, vals)
end
end
isempty(in_vals) && stat.ticks==:auto && return
in_vals = Iterators.flatten(in_vals)
# consider forced tick marks
if stat.ticks != :auto
minval = minimum(skipmissing([minval;stat.ticks]))
maxval = maximum(skipmissing([maxval;stat.ticks]))
end
# TODO: handle the outliers aesthetic
n = Gadfly.concrete_length(in_vals)
# check the x/yviewmin/max pesudo-aesthetics
if stat.axis == "x"
if aes.xviewmin != nothing
minval = min(minval, aes.xviewmin)
end
if aes.xviewmax != nothing
maxval = max(maxval, aes.xviewmax)
end
elseif stat.axis == "y"
if aes.yviewmin != nothing
minval = min(minval, aes.yviewmin)
end
if aes.yviewmax != nothing
maxval = max(maxval, aes.yviewmax)
end
end
# take into account a forced viewport in cartesian coordinates.
strict_span = false
if typeof(coord) == Coord.Cartesian
if stat.axis == "x"
if coord.xmin !== nothing
minval = coord.xmin
strict_span = true
end
if coord.xmax !== nothing
maxval = coord.xmax
strict_span = true
end
elseif stat.axis == "y"
if coord.ymin !== nothing
minval = coord.ymin
strict_span = true
end
if coord.ymax !== nothing
maxval = coord.ymax
strict_span = true
end
end
end
# all the input values in order.
if stat.ticks != :auto
grids = ticks = stat.ticks
viewmin = minval
viewmax = maxval
tickvisible = fill(true, length(ticks))
tickscale = fill(1.0, length(ticks))
elseif categorical
ticks = Set{Int}()
for val in in_vals
val>0 && push!(ticks, round(Int, val))
end
ticks = Int[t for t in ticks]
sort!(ticks)
grids = (ticks .- 0.5)[2:end]
viewmin = minimum(ticks)
viewmax = maximum(ticks)
tickvisible = fill(true, length(ticks))
tickscale = fill(1.0, length(ticks))
else
minval, maxval = promote(minval, maxval)
ticks, viewmin, viewmax = Gadfly.optimize_ticks(minval, maxval,
granularity_weight=stat.granularity_weight,
simplicity_weight=stat.simplicity_weight,
coverage_weight=stat.coverage_weight,
niceness_weight=stat.niceness_weight,
strict_span=strict_span)
grids = ticks
multiticks = Gadfly.multilevel_ticks(viewmin, viewmax)
tickcount = length(ticks) + sum([length(ts) for ts in values(multiticks)])
tickvisible = Array{Bool}(undef, tickcount)
tickscale = Array{Float64}(undef, tickcount)
i = 1
for t in ticks
tickscale[i] = 1.0
tickvisible[i] = viewmin <= t <= viewmax
i += 1
end
for (scale, ts) in multiticks, t in ts
push!(ticks, t)
tickvisible[i] = false
tickscale[i] = scale
i += 1
end
end
# We use the first label function we find for any of the aesthetics. I'm not
# positive this is the right thing to do, or would would be.
labeler = getfield(aes, Symbol(stat.axis, "_label"))
setfield!(aes, Symbol(stat.axis, "tick"), ticks)
setfield!(aes, Symbol(stat.axis, "grid"), grids)
setfield!(aes, Symbol(stat.axis, "tick_label"), labeler)
setfield!(aes, Symbol(stat.axis, "tickvisible"), tickvisible)
setfield!(aes, Symbol(stat.axis, "tickscale"), tickscale)