-
-
Notifications
You must be signed in to change notification settings - Fork 290
/
axis.jl
1378 lines (1161 loc) · 48.7 KB
/
axis.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
function block_docs(::Type{Axis})
"""
A 2D axis which can be plotted into.
## Constructors
```julia
Axis(fig_or_scene; palette = nothing, kwargs...)
```
## Examples
```julia
ax = Axis(fig[1, 1])
```
"""
end
function update_gridlines!(grid_obs::Observable{Vector{Point2f}}, offset::Point2f, tickpositions::Vector{Point2f})
result = grid_obs[]
empty!(result) # reuse array for less allocations
for gridstart in tickpositions
opposite_tickpos = gridstart .+ offset
push!(result, gridstart, opposite_tickpos)
end
notify(grid_obs)
return
end
function process_axis_event(ax, event)
for (active, interaction) in values(ax.interactions)
if active
maybe_consume = process_interaction(interaction, event, ax)
maybe_consume == Consume(true) && return Consume(true)
end
end
return Consume(false)
end
function register_events!(ax, scene)
mouseeventhandle = addmouseevents!(scene)
setfield!(ax, :mouseeventhandle, mouseeventhandle)
scrollevents = Observable(ScrollEvent(0, 0))
setfield!(ax, :scrollevents, scrollevents)
keysevents = Observable(KeysEvent(Set()))
setfield!(ax, :keysevents, keysevents)
evs = events(scene)
on(scene, evs.scroll) do s
if is_mouseinside(scene)
scrollevents[] = ScrollEvent(s[1], s[2])
return Consume(true)
end
return Consume(false)
end
# TODO this should probably just forward KeyEvent from Makie
on(scene, evs.keyboardbutton) do e
keysevents[] = KeysEvent(evs.keyboardstate)
return Consume(false)
end
interactions = Dict{Symbol, Tuple{Bool, Any}}()
setfield!(ax, :interactions, interactions)
onany(process_axis_event, scene, ax, mouseeventhandle.obs)
onany(process_axis_event, scene, ax, scrollevents)
onany(process_axis_event, scene, ax, keysevents)
register_interaction!(ax, :rectanglezoom, RectangleZoom(ax))
register_interaction!(ax, :limitreset, LimitReset())
register_interaction!(ax, :scrollzoom, ScrollZoom(0.1, 0.2))
register_interaction!(ax, :dragpan, DragPan(0.2))
return
end
function update_axis_camera(camera::Camera, t, lims, xrev::Bool, yrev::Bool)
nearclip = -10_000f0
farclip = 10_000f0
# we are computing transformed camera position, so this isn't space dependent
tlims = Makie.apply_transform(t, lims)
left, bottom = minimum(tlims)
right, top = maximum(tlims)
leftright = xrev ? (right, left) : (left, right)
bottomtop = yrev ? (top, bottom) : (bottom, top)
projection = Makie.orthographicprojection(
Float32,
leftright...,
bottomtop..., nearclip, farclip)
Makie.set_proj_view!(camera, projection, Makie.Mat4f(Makie.I))
return
end
function calculate_title_position(area, titlegap, subtitlegap, align, xaxisposition, xaxisprotrusion, _, ax, subtitlet)
local x::Float32 = if align === :center
area.origin[1] + area.widths[1] / 2
elseif align === :left
area.origin[1]
elseif align === :right
area.origin[1] + area.widths[1]
else
error("Title align $align not supported.")
end
local subtitlespace::Float32 = if ax.subtitlevisible[] && !iswhitespace(ax.subtitle[])
boundingbox(subtitlet).widths[2] + subtitlegap
else
0f0
end
local yoffset::Float32 = top(area) + titlegap + (xaxisposition === :top ? xaxisprotrusion : 0f0) +
subtitlespace
return Point2f(x, yoffset)
end
function compute_protrusions(title, titlesize, titlegap, titlevisible, spinewidth,
topspinevisible, bottomspinevisible, leftspinevisible, rightspinevisible,
xaxisprotrusion, yaxisprotrusion, xaxisposition, yaxisposition,
subtitle, subtitlevisible, subtitlesize, subtitlegap, titlelineheight, subtitlelineheight,
subtitlet, titlet)
local left::Float32, right::Float32, bottom::Float32, top::Float32 = 0f0, 0f0, 0f0, 0f0
if xaxisposition === :bottom
bottom = xaxisprotrusion
else
top = xaxisprotrusion
end
titleheight = boundingbox(titlet).widths[2] + titlegap
subtitleheight = boundingbox(subtitlet).widths[2] + subtitlegap
titlespace = if !titlevisible || iswhitespace(title)
0f0
else
titleheight
end
subtitlespace = if !subtitlevisible || iswhitespace(subtitle)
0f0
else
subtitleheight
end
top += titlespace + subtitlespace
if yaxisposition === :left
left = yaxisprotrusion
else
right = yaxisprotrusion
end
return GridLayoutBase.RectSides{Float32}(left, right, bottom, top)
end
function initialize_block!(ax::Axis; palette = nothing)
blockscene = ax.blockscene
elements = Dict{Symbol, Any}()
ax.elements = elements
if palette === nothing
palette = haskey(blockscene.theme, :palette) ? deepcopy(blockscene.theme[:palette]) : copy(Makie.default_palettes)
end
ax.palette = palette isa Attributes ? palette : Attributes(palette)
# initialize either with user limits, or pick defaults based on scales
# so that we don't immediately error
targetlimits = Observable{Rect2f}(defaultlimits(ax.limits[], ax.xscale[], ax.yscale[]))
finallimits = Observable{Rect2f}(targetlimits[]; ignore_equal_values=true)
setfield!(ax, :targetlimits, targetlimits)
setfield!(ax, :finallimits, finallimits)
ax.cycler = Cycler()
# the first thing to do when setting a new scale is
# resetting the limits because simply through expanding they might be invalid for log
onany(blockscene, ax.xscale, ax.yscale) do _, _
reset_limits!(ax)
end
on(blockscene, targetlimits) do lims
# this should validate the targetlimits before anything else happens with them
# so there should be nothing before this lifting `targetlimits`
# we don't use finallimits because that's one step later and you
# already shouldn't set invalid targetlimits (even if they could
# theoretically be adjusted to fit somehow later?)
# and this way we can error pretty early
validate_limits_for_scales(lims, ax.xscale[], ax.yscale[])
end
scenearea = sceneareanode!(ax.layoutobservables.computedbbox, finallimits, ax.aspect)
scene = Scene(blockscene, px_area=scenearea)
ax.scene = scene
# TODO: replace with mesh, however, CairoMakie needs a poly path for this signature
# so it doesn't rasterize the scene
background = poly!(blockscene, scenearea; color=ax.backgroundcolor, inspectable=false, shading=false, strokecolor=:transparent)
translate!(background, 0, 0, -100)
elements[:background] = background
block_limit_linking = Observable(false)
setfield!(ax, :block_limit_linking, block_limit_linking)
ax.xaxislinks = Axis[]
ax.yaxislinks = Axis[]
xgridnode = Observable(Point2f[]; ignore_equal_values=true)
xgridlines = linesegments!(
blockscene, xgridnode, linewidth = ax.xgridwidth, visible = ax.xgridvisible,
color = ax.xgridcolor, linestyle = ax.xgridstyle, inspectable = false
)
# put gridlines behind the zero plane so they don't overlay plots
translate!(xgridlines, 0, 0, -10)
elements[:xgridlines] = xgridlines
xminorgridnode = Observable(Point2f[]; ignore_equal_values=true)
xminorgridlines = linesegments!(
blockscene, xminorgridnode, linewidth = ax.xminorgridwidth, visible = ax.xminorgridvisible,
color = ax.xminorgridcolor, linestyle = ax.xminorgridstyle, inspectable = false
)
# put gridlines behind the zero plane so they don't overlay plots
translate!(xminorgridlines, 0, 0, -10)
elements[:xminorgridlines] = xminorgridlines
ygridnode = Observable(Point2f[]; ignore_equal_values=true)
ygridlines = linesegments!(
blockscene, ygridnode, linewidth = ax.ygridwidth, visible = ax.ygridvisible,
color = ax.ygridcolor, linestyle = ax.ygridstyle, inspectable = false
)
# put gridlines behind the zero plane so they don't overlay plots
translate!(ygridlines, 0, 0, -10)
elements[:ygridlines] = ygridlines
yminorgridnode = Observable(Point2f[]; ignore_equal_values=true)
yminorgridlines = linesegments!(
blockscene, yminorgridnode, linewidth = ax.yminorgridwidth, visible = ax.yminorgridvisible,
color = ax.yminorgridcolor, linestyle = ax.yminorgridstyle, inspectable = false
)
# put gridlines behind the zero plane so they don't overlay plots
translate!(yminorgridlines, 0, 0, -10)
elements[:yminorgridlines] = yminorgridlines
onany(blockscene, ax.xscale, ax.yscale) do xsc, ysc
scene.transformation.transform_func[] = (xsc, ysc)
return
end
notify(ax.xscale)
onany(update_axis_camera, camera(scene), scene.transformation.transform_func, finallimits, ax.xreversed, ax.yreversed)
xaxis_endpoints = lift(blockscene, ax.xaxisposition, scene.px_area;
ignore_equal_values=true) do xaxisposition, area
if xaxisposition === :bottom
return bottomline(Rect2f(area))
elseif xaxisposition === :top
return topline(Rect2f(area))
else
error("Invalid xaxisposition $xaxisposition")
end
end
yaxis_endpoints = lift(blockscene, ax.yaxisposition, scene.px_area;
ignore_equal_values=true) do yaxisposition, area
if yaxisposition === :left
return leftline(Rect2f(area))
elseif yaxisposition === :right
return rightline(Rect2f(area))
else
error("Invalid yaxisposition $yaxisposition")
end
end
xaxis_flipped = lift(x -> x === :top, blockscene, ax.xaxisposition; ignore_equal_values=true)
yaxis_flipped = lift(x -> x === :right, blockscene, ax.yaxisposition; ignore_equal_values=true)
xspinevisible = lift(blockscene, xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible;
ignore_equal_values=true) do xflip, bv, tv
xflip ? tv : bv
end
xoppositespinevisible = lift(blockscene, xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible;
ignore_equal_values=true) do xflip, bv, tv
xflip ? bv : tv
end
yspinevisible = lift(blockscene, yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible;
ignore_equal_values=true) do yflip, lv, rv
yflip ? rv : lv
end
yoppositespinevisible = lift(blockscene, yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible;
ignore_equal_values=true) do yflip, lv, rv
yflip ? lv : rv
end
xspinecolor = lift(blockscene, xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor;
ignore_equal_values=true) do xflip, bc, tc
xflip ? tc : bc
end
xoppositespinecolor = lift(blockscene, xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor;
ignore_equal_values=true) do xflip, bc, tc
xflip ? bc : tc
end
yspinecolor = lift(blockscene, yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor;
ignore_equal_values=true) do yflip, lc, rc
yflip ? rc : lc
end
yoppositespinecolor = lift(blockscene, yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor;
ignore_equal_values=true) do yflip, lc, rc
yflip ? lc : rc
end
xlims = lift(xlimits, blockscene, finallimits; ignore_equal_values=true)
ylims = lift(ylimits, blockscene, finallimits; ignore_equal_values=true)
xaxis = LineAxis(blockscene, endpoints = xaxis_endpoints, limits = xlims,
flipped = xaxis_flipped, ticklabelrotation = ax.xticklabelrotation,
ticklabelalign = ax.xticklabelalign, labelsize = ax.xlabelsize,
labelpadding = ax.xlabelpadding, ticklabelpad = ax.xticklabelpad, labelvisible = ax.xlabelvisible,
label = ax.xlabel, labelfont = ax.xlabelfont, labelrotation = ax.xlabelrotation, ticklabelfont = ax.xticklabelfont, ticklabelcolor = ax.xticklabelcolor, labelcolor = ax.xlabelcolor, tickalign = ax.xtickalign,
ticklabelspace = ax.xticklabelspace, ticks = ax.xticks, tickformat = ax.xtickformat, ticklabelsvisible = ax.xticklabelsvisible,
ticksvisible = ax.xticksvisible, spinevisible = xspinevisible, spinecolor = xspinecolor, spinewidth = ax.spinewidth,
ticklabelsize = ax.xticklabelsize, trimspine = ax.xtrimspine, ticksize = ax.xticksize,
reversed = ax.xreversed, tickwidth = ax.xtickwidth, tickcolor = ax.xtickcolor,
minorticksvisible = ax.xminorticksvisible, minortickalign = ax.xminortickalign, minorticksize = ax.xminorticksize, minortickwidth = ax.xminortickwidth, minortickcolor = ax.xminortickcolor, minorticks = ax.xminorticks, scale = ax.xscale,
)
ax.xaxis = xaxis
yaxis = LineAxis(blockscene, endpoints = yaxis_endpoints, limits = ylims,
flipped = yaxis_flipped, ticklabelrotation = ax.yticklabelrotation,
ticklabelalign = ax.yticklabelalign, labelsize = ax.ylabelsize,
labelpadding = ax.ylabelpadding, ticklabelpad = ax.yticklabelpad, labelvisible = ax.ylabelvisible,
label = ax.ylabel, labelfont = ax.ylabelfont, labelrotation = ax.ylabelrotation, ticklabelfont = ax.yticklabelfont, ticklabelcolor = ax.yticklabelcolor, labelcolor = ax.ylabelcolor, tickalign = ax.ytickalign,
ticklabelspace = ax.yticklabelspace, ticks = ax.yticks, tickformat = ax.ytickformat, ticklabelsvisible = ax.yticklabelsvisible,
ticksvisible = ax.yticksvisible, spinevisible = yspinevisible, spinecolor = yspinecolor, spinewidth = ax.spinewidth,
trimspine = ax.ytrimspine, ticklabelsize = ax.yticklabelsize, ticksize = ax.yticksize, flip_vertical_label = ax.flip_ylabel, reversed = ax.yreversed, tickwidth = ax.ytickwidth,
tickcolor = ax.ytickcolor,
minorticksvisible = ax.yminorticksvisible, minortickalign = ax.yminortickalign, minorticksize = ax.yminorticksize, minortickwidth = ax.yminortickwidth, minortickcolor = ax.yminortickcolor, minorticks = ax.yminorticks, scale = ax.yscale,
)
ax.yaxis = yaxis
xoppositelinepoints = lift(blockscene, scene.px_area, ax.spinewidth, ax.xaxisposition;
ignore_equal_values=true) do r, sw, xaxpos
if xaxpos === :top
y = bottom(r)
p1 = Point2f(left(r) - 0.5sw, y)
p2 = Point2f(right(r) + 0.5sw, y)
return [p1, p2]
else
y = top(r)
p1 = Point2f(left(r) - 0.5sw, y)
p2 = Point2f(right(r) + 0.5sw, y)
return [p1, p2]
end
end
yoppositelinepoints = lift(blockscene, scene.px_area, ax.spinewidth, ax.yaxisposition;
ignore_equal_values=true) do r, sw, yaxpos
if yaxpos === :right
x = left(r)
p1 = Point2f(x, bottom(r) - 0.5sw)
p2 = Point2f(x, top(r) + 0.5sw)
return [p1, p2]
else
x = right(r)
p1 = Point2f(x, bottom(r) - 0.5sw)
p2 = Point2f(x, top(r) + 0.5sw)
return [p1, p2]
end
end
xticksmirrored = lift(mirror_ticks, blockscene, xaxis.tickpositions, ax.xticksize, ax.xtickalign,
Ref(scene.px_area), :x, ax.xaxisposition[])
xticksmirrored_lines = linesegments!(blockscene, xticksmirrored, visible = @lift($(ax.xticksmirrored) && $(ax.xticksvisible)),
linewidth = ax.xtickwidth, color = ax.xtickcolor)
translate!(xticksmirrored_lines, 0, 0, 10)
yticksmirrored = lift(mirror_ticks, blockscene, yaxis.tickpositions, ax.yticksize, ax.ytickalign,
Ref(scene.px_area), :y, ax.yaxisposition[])
yticksmirrored_lines = linesegments!(blockscene, yticksmirrored, visible = @lift($(ax.yticksmirrored) && $(ax.yticksvisible)),
linewidth = ax.ytickwidth, color = ax.ytickcolor)
translate!(yticksmirrored_lines, 0, 0, 10)
xminorticksmirrored = lift(mirror_ticks, blockscene, xaxis.minortickpositions, ax.xminorticksize,
ax.xminortickalign, Ref(scene.px_area), :x, ax.xaxisposition[])
xminorticksmirrored_lines = linesegments!(blockscene, xminorticksmirrored, visible = @lift($(ax.xticksmirrored) && $(ax.xminorticksvisible)),
linewidth = ax.xminortickwidth, color = ax.xminortickcolor)
translate!(xminorticksmirrored_lines, 0, 0, 10)
yminorticksmirrored = lift(mirror_ticks, blockscene, yaxis.minortickpositions, ax.yminorticksize,
ax.yminortickalign, Ref(scene.px_area), :y, ax.yaxisposition[])
yminorticksmirrored_lines = linesegments!(blockscene, yminorticksmirrored, visible = @lift($(ax.yticksmirrored) && $(ax.yminorticksvisible)),
linewidth = ax.yminortickwidth, color = ax.yminortickcolor)
translate!(yminorticksmirrored_lines, 0, 0, 10)
xoppositeline = linesegments!(blockscene, xoppositelinepoints, linewidth = ax.spinewidth,
visible = xoppositespinevisible, color = xoppositespinecolor, inspectable = false,
linestyle = nothing)
elements[:xoppositeline] = xoppositeline
translate!(xoppositeline, 0, 0, 20)
yoppositeline = linesegments!(blockscene, yoppositelinepoints, linewidth = ax.spinewidth,
visible = yoppositespinevisible, color = yoppositespinecolor, inspectable = false,
linestyle = nothing)
elements[:yoppositeline] = yoppositeline
translate!(yoppositeline, 0, 0, 20)
onany(blockscene, xaxis.tickpositions, scene.px_area) do tickpos, area
local pxheight::Float32 = height(area)
local offset::Float32 = ax.xaxisposition[] === :bottom ? pxheight : -pxheight
update_gridlines!(xgridnode, Point2f(0, offset), tickpos)
end
onany(blockscene, yaxis.tickpositions, scene.px_area) do tickpos, area
local pxwidth::Float32 = width(area)
local offset::Float32 = ax.yaxisposition[] === :left ? pxwidth : -pxwidth
update_gridlines!(ygridnode, Point2f(offset, 0), tickpos)
end
onany(blockscene, xaxis.minortickpositions, scene.px_area) do tickpos, area
local pxheight::Float32 = height(scene.px_area[])
local offset::Float32 = ax.xaxisposition[] === :bottom ? pxheight : -pxheight
update_gridlines!(xminorgridnode, Point2f(0, offset), tickpos)
end
onany(blockscene, yaxis.minortickpositions, scene.px_area) do tickpos, area
local pxwidth::Float32 = width(scene.px_area[])
local offset::Float32 = ax.yaxisposition[] === :left ? pxwidth : -pxwidth
update_gridlines!(yminorgridnode, Point2f(offset, 0), tickpos)
end
subtitlepos = lift(blockscene, scene.px_area, ax.titlegap, ax.titlealign, ax.xaxisposition,
xaxis.protrusion;
ignore_equal_values=true) do a,
titlegap, align, xaxisposition, xaxisprotrusion
x = if align === :center
a.origin[1] + a.widths[1] / 2
elseif align === :left
a.origin[1]
elseif align === :right
a.origin[1] + a.widths[1]
else
error("Title align $align not supported.")
end
yoffset = top(a) + titlegap + (xaxisposition === :top ? xaxisprotrusion : 0f0)
return Point2f(x, yoffset)
end
titlealignnode = lift(blockscene, ax.titlealign; ignore_equal_values=true) do align
(align, :bottom)
end
subtitlet = text!(
blockscene, subtitlepos,
text = ax.subtitle,
visible = ax.subtitlevisible,
fontsize = ax.subtitlesize,
align = titlealignnode,
font = ax.subtitlefont,
color = ax.subtitlecolor,
lineheight = ax.subtitlelineheight,
markerspace = :data,
inspectable = false)
titlepos = lift(calculate_title_position, blockscene, scene.px_area, ax.titlegap, ax.subtitlegap,
ax.titlealign, ax.xaxisposition, xaxis.protrusion, ax.subtitlelineheight, ax, subtitlet; ignore_equal_values=true)
titlet = text!(
blockscene, titlepos,
text = ax.title,
visible = ax.titlevisible,
fontsize = ax.titlesize,
align = titlealignnode,
font = ax.titlefont,
color = ax.titlecolor,
lineheight = ax.titlelineheight,
markerspace = :data,
inspectable = false)
elements[:title] = titlet
map!(compute_protrusions, blockscene, ax.layoutobservables.protrusions, ax.title, ax.titlesize,
ax.titlegap, ax.titlevisible, ax.spinewidth,
ax.topspinevisible, ax.bottomspinevisible, ax.leftspinevisible, ax.rightspinevisible,
xaxis.protrusion, yaxis.protrusion, ax.xaxisposition, ax.yaxisposition,
ax.subtitle, ax.subtitlevisible, ax.subtitlesize, ax.subtitlegap,
ax.titlelineheight, ax.subtitlelineheight, subtitlet, titlet)
# trigger first protrusions with one of the observables
notify(ax.title)
# trigger bboxnode so the axis layouts itself even if not connected to a
# layout
notify(ax.layoutobservables.suggestedbbox)
register_events!(ax, scene)
# these are the user defined limits
on(blockscene, ax.limits) do mlims
reset_limits!(ax)
end
# these are the limits that we try to target, but they can be changed for correct aspects
on(blockscene, targetlimits) do tlims
update_linked_limits!(block_limit_linking, ax.xaxislinks, ax.yaxislinks, tlims)
end
# compute limits that adhere to the limit aspect ratio whenever the targeted
# limits or the scene size change, because both influence the displayed ratio
onany(blockscene, scene.px_area, targetlimits) do pxa, lims
adjustlimits!(ax)
end
# trigger limit pipeline once, with manual finallimits if they haven't changed from
# their initial value as they need to be triggered at least once to correctly set up
# projection matrices etc.
fl = finallimits[]
notify(ax.limits)
if fl == finallimits[]
notify(finallimits)
end
return ax
end
function mirror_ticks(tickpositions, ticksize, tickalign, px_area, side, axisposition)
a = px_area[][]
if side === :x
opp = axisposition === :bottom ? top(a) : bottom(a)
sign = axisposition === :bottom ? 1 : -1
else
opp = axisposition === :left ? right(a) : left(a)
sign = axisposition === :left ? 1 : -1
end
d = ticksize * sign
points = Vector{Point2f}(undef, 2*length(tickpositions))
if side === :x
for (i, (x, _)) in enumerate(tickpositions)
points[2i-1] = Point2f(x, opp - d * tickalign)
points[2i] = Point2f(x, opp + d - d * tickalign)
end
else
for (i, (_, y)) in enumerate(tickpositions)
points[2i-1] = Point2f(opp - d * tickalign, y)
points[2i] = Point2f(opp + d - d * tickalign, y)
end
end
return points
end
"""
reset_limits!(ax; xauto = true, yauto = true)
Resets the axis limits depending on the value of `ax.limits`.
If one of the two components of limits is nothing,
that value is either copied from the targetlimits if `xauto` or `yauto` is false,
respectively, or it is determined automatically from the plots in the axis.
If one of the components is a tuple of two numbers, those are used directly.
"""
function reset_limits!(ax; xauto = true, yauto = true, zauto = true)
mlims = convert_limit_attribute(ax.limits[])
if ax isa Axis
mxlims, mylims = mlims::Tuple{Any, Any}
elseif ax isa Axis3
mxlims, mylims, mzlims = mlims::Tuple{Any, Any, Any}
else
error()
end
xlims = if isnothing(mxlims) || mxlims[1] === nothing || mxlims[2] === nothing
l = if xauto
xautolimits(ax)
else
minimum(ax.targetlimits[])[1], maximum(ax.targetlimits[])[1]
end
if mxlims === nothing
l
else
lo = mxlims[1] === nothing ? l[1] : mxlims[1]
hi = mxlims[2] === nothing ? l[2] : mxlims[2]
(lo, hi)
end
else
convert(Tuple{Float32, Float32}, tuple(mxlims...))
end
ylims = if isnothing(mylims) || mylims[1] === nothing || mylims[2] === nothing
l = if yauto
yautolimits(ax)
else
minimum(ax.targetlimits[])[2], maximum(ax.targetlimits[])[2]
end
if mylims === nothing
l
else
lo = mylims[1] === nothing ? l[1] : mylims[1]
hi = mylims[2] === nothing ? l[2] : mylims[2]
(lo, hi)
end
else
convert(Tuple{Float32, Float32}, tuple(mylims...))
end
if ax isa Axis3
zlims = if isnothing(mzlims) || mzlims[1] === nothing || mzlims[2] === nothing
l = if zauto
zautolimits(ax)
else
minimum(ax.targetlimits[])[3], maximum(ax.targetlimits[])[3]
end
if mzlims === nothing
l
else
lo = mzlims[1] === nothing ? l[1] : mzlims[1]
hi = mzlims[2] === nothing ? l[2] : mzlims[2]
(lo, hi)
end
else
convert(Tuple{Float32, Float32}, tuple(mzlims...))
end
end
if !(xlims[1] <= xlims[2])
error("Invalid x-limits as xlims[1] <= xlims[2] is not met for $xlims.")
end
if !(ylims[1] <= ylims[2])
error("Invalid y-limits as ylims[1] <= ylims[2] is not met for $ylims.")
end
if ax isa Axis3
if !(zlims[1] <= zlims[2])
error("Invalid z-limits as zlims[1] <= zlims[2] is not met for $zlims.")
end
end
tlims = if ax isa Axis
BBox(xlims..., ylims...)
elseif ax isa Axis3
Rect3f(
Vec3f(xlims[1], ylims[1], zlims[1]),
Vec3f(xlims[2] - xlims[1], ylims[2] - ylims[1], zlims[2] - zlims[1]),
)
end
ax.targetlimits[] = tlims
nothing
end
# this is so users can do limits = (left, right, bottom, top)
function convert_limit_attribute(lims::Tuple{Any, Any, Any, Any})
(lims[1:2], lims[3:4])
end
function convert_limit_attribute(lims::Tuple{Any, Any})
lims
end
can_be_current_axis(ax::Axis) = true
function validate_limits_for_scales(lims::Rect, xsc, ysc)
mi = minimum(lims)
ma = maximum(lims)
xlims = (mi[1], ma[1])
ylims = (mi[2], ma[2])
if !validate_limits_for_scale(xlims, xsc)
error("Invalid x-limits $xlims for scale $xsc which is defined on the interval $(defined_interval(xsc))")
end
if !validate_limits_for_scale(ylims, ysc)
error("Invalid y-limits $ylims for scale $ysc which is defined on the interval $(defined_interval(ysc))")
end
nothing
end
validate_limits_for_scale(lims, scale) = all(x -> x in defined_interval(scale), lims)
palettesyms(cycle::Cycle) = [c[2] for c in cycle.cycle]
attrsyms(cycle::Cycle) = [c[1] for c in cycle.cycle]
function get_cycler_index!(c::Cycler, P::Type)
if !haskey(c.counters, P)
c.counters[P] = 1
else
c.counters[P] += 1
end
end
function get_cycle_for_plottype(allattrs, P)::Cycle
psym = MakieCore.plotsym(P)
plottheme = Makie.default_theme(nothing, P)
cycle_raw = if haskey(allattrs, :cycle)
allattrs.cycle[]
else
global_theme_cycle = theme(psym)
if !isnothing(global_theme_cycle) && haskey(global_theme_cycle, :cycle)
global_theme_cycle.cycle[]
else
haskey(plottheme, :cycle) ? plottheme.cycle[] : nothing
end
end
if isnothing(cycle_raw)
Cycle([])
elseif cycle_raw isa Cycle
cycle_raw
else
Cycle(cycle_raw)
end
end
function add_cycle_attributes!(allattrs, P, cycle::Cycle, cycler::Cycler, palette::Attributes)
# check if none of the cycled attributes of this plot
# were passed manually, because we don't use the cycler
# if any of the cycled attributes were specified manually
no_cycle_attribute_passed = !any(keys(allattrs)) do key
any(syms -> key in syms, attrsyms(cycle))
end
# check if any attributes were passed as `Cycled` entries
# because if there were any, these are looked up directly
# in the cycler without advancing the counter etc.
manually_cycled_attributes = filter(keys(allattrs)) do key
to_value(allattrs[key]) isa Cycled
end
# if there are any manually cycled attributes, we don't do the normal
# cycling but only look up exactly the passed attributes
cycle_attrsyms = attrsyms(cycle)
if !isempty(manually_cycled_attributes)
# an attribute given as Cycled needs to be present in the cycler,
# otherwise there's no cycle in which to look up a value
for k in manually_cycled_attributes
if !any(x -> k in x, cycle_attrsyms)
error("Attribute `$k` was passed with an explicit `Cycled` value, but $k is not specified in the cycler for this plot type $P.")
end
end
palettes = [palette[sym][] for sym in palettesyms(cycle)]
for sym in manually_cycled_attributes
isym = findfirst(syms -> sym in syms, attrsyms(cycle))
index = allattrs[sym][].i
# replace the Cycled values with values from the correct palettes
# at the index inside the Cycled object
allattrs[sym] = if cycle.covary
palettes[isym][mod1(index, length(palettes[isym]))]
else
cis = CartesianIndices(Tuple(length(p) for p in palettes))
n = length(cis)
k = mod1(index, n)
idx = Tuple(cis[k])
palettes[isym][idx[isym]]
end
end
elseif no_cycle_attribute_passed
index = get_cycler_index!(cycler, P)
palettes = [palette[sym][] for sym in palettesyms(cycle)]
for (isym, syms) in enumerate(attrsyms(cycle))
for sym in syms
allattrs[sym] = if cycle.covary
palettes[isym][mod1(index, length(palettes[isym]))]
else
cis = CartesianIndices(Tuple(length(p) for p in palettes))
n = length(cis)
k = mod1(index, n)
idx = Tuple(cis[k])
palettes[isym][idx[isym]]
end
end
end
end
end
function Makie.plot!(
la::Axis, P::Makie.PlotFunc,
attributes::Makie.Attributes, args...;
kw_attributes...)
allattrs = merge(attributes, Attributes(kw_attributes))
_disallow_keyword(:axis, allattrs)
_disallow_keyword(:figure, allattrs)
cycle = get_cycle_for_plottype(allattrs, P)
add_cycle_attributes!(allattrs, P, cycle, la.cycler, la.palette)
plot = Makie.plot!(la.scene, P, allattrs, args...)
# some area-like plots basically always look better if they cover the whole plot area.
# adjust the limit margins in those cases automatically.
needs_tight_limits(plot) && tightlimits!(la)
if is_open_or_any_parent(la.scene)
reset_limits!(la)
end
plot
end
is_open_or_any_parent(s::Scene) = isopen(s) || is_open_or_any_parent(s.parent)
is_open_or_any_parent(::Nothing) = false
function Makie.plot!(P::Makie.PlotFunc, ax::Axis, args...; kw_attributes...)
attributes = Makie.Attributes(kw_attributes)
Makie.plot!(ax, P, attributes, args...)
end
needs_tight_limits(@nospecialize any) = false
needs_tight_limits(::Union{Heatmap, Image}) = true
function needs_tight_limits(c::Contourf)
# we know that all values are included and the contourf is rectangular
# otherwise here it could be in an arbitrary shape
return c.levels[] isa Int
end
function expandbboxwithfractionalmargins(bb, margins)
newwidths = bb.widths .* (1f0 .+ margins)
diffs = newwidths .- bb.widths
neworigin = bb.origin .- (0.5f0 .* diffs)
return Rect2f(neworigin, newwidths)
end
limitunion(lims1, lims2) = (min(lims1..., lims2...), max(lims1..., lims2...))
function expandlimits(lims, margin_low, margin_high, scale)
# expand limits so that the margins are applied at the current axis scale
limsordered = (min(lims[1], lims[2]), max(lims[1], lims[2]))
lims_scaled = scale.(limsordered)
w_scaled = lims_scaled[2] - lims_scaled[1]
d_low_scaled = w_scaled * margin_low
d_high_scaled = w_scaled * margin_high
inverse = Makie.inverse_transform(scale)
lims = inverse.((lims_scaled[1] - d_low_scaled, lims_scaled[2] + d_high_scaled))
# guard against singular limits from something like a vline or hline
if lims[2] - lims[1] ≈ 0
# this works for log as well
# we look at the distance to zero in scaled space
# then try to center the value between that zero and the value
# that is the same scaled distance away on the other side
# which centers the singular value optically
zerodist = abs(scale(lims[1]))
# for 0 in linear space this doesn't work so here we just expand to -1, 1
if zerodist ≈ 0 && scale === identity
lims = (-one(lims[1]), one(lims[1]))
else
lims = inverse.(scale.(lims) .+ (-zerodist, zerodist))
end
end
lims
end
function getlimits(la::Axis, dim)
# find all plots that don't have exclusion attributes set
# for this dimension
if !(dim in (1, 2))
error("Dimension $dim not allowed. Only 1 or 2.")
end
function exclude(plot)
# only use plots with autolimits = true
to_value(get(plot, dim == 1 ? :xautolimits : :yautolimits, true)) || return true
# only if they use data coordinates
is_data_space(to_value(get(plot, :space, :data))) || return true
# only use visible plots for limits
return !to_value(get(plot, :visible, true))
end
# get all data limits, minus the excluded plots
boundingbox = Makie.data_limits(la.scene, exclude)
# if there are no bboxes remaining, `nothing` signals that no limits could be determined
Makie.isfinite_rect(boundingbox) || return nothing
# otherwise start with the first box
mini, maxi = minimum(boundingbox), maximum(boundingbox)
return (mini[dim], maxi[dim])
end
getxlimits(la::Axis) = getlimits(la, 1)
getylimits(la::Axis) = getlimits(la, 2)
function update_linked_limits!(block_limit_linking, xaxislinks, yaxislinks, tlims)
thisxlims = xlimits(tlims)
thisylims = ylimits(tlims)
# only change linked axis if not prohibited from doing so because
# we're currently being updated by another axis' link
if !block_limit_linking[]
bothlinks = intersect(xaxislinks, yaxislinks)
xlinks = setdiff(xaxislinks, yaxislinks)
ylinks = setdiff(yaxislinks, xaxislinks)
for link in bothlinks
otherlims = link.targetlimits[]
if tlims != otherlims
link.block_limit_linking[] = true
link.targetlimits[] = tlims
link.block_limit_linking[] = false
end
end
for xlink in xlinks
otherlims = xlink.targetlimits[]
otherxlims = limits(otherlims, 1)
otherylims = limits(otherlims, 2)
if thisxlims != otherxlims
xlink.block_limit_linking[] = true
xlink.targetlimits[] = BBox(thisxlims[1], thisxlims[2], otherylims[1], otherylims[2])
xlink.block_limit_linking[] = false
end
end
for ylink in ylinks
otherlims = ylink.targetlimits[]
otherxlims = limits(otherlims, 1)
otherylims = limits(otherlims, 2)
if thisylims != otherylims
ylink.block_limit_linking[] = true
ylink.targetlimits[] = BBox(otherxlims[1], otherxlims[2], thisylims[1], thisylims[2])
ylink.block_limit_linking[] = false
end
end
end
end
"""
autolimits!(la::Axis)
Reset manually specified limits of `la` to an automatically determined rectangle, that depends on the data limits of all plot objects in the axis, as well as the autolimit margins for x and y axis.
"""
function autolimits!(ax::Axis)
ax.limits[] = (nothing, nothing)
return
end
function autolimits(ax::Axis, dim::Integer)
# try getting x limits for the axis and then union them with linked axes
lims = getlimits(ax, dim)
links = dim == 1 ? ax.xaxislinks : ax.yaxislinks
for link in links
if isnothing(lims)
lims = getlimits(link, dim)
else
newlims = getlimits(link, dim)
if !isnothing(newlims)
lims = limitunion(lims, newlims)
end
end
end
dimsym = dim == 1 ? :x : :y
scale = getproperty(ax, Symbol(dimsym, :scale))[]
margin = getproperty(ax, Symbol(dimsym, :autolimitmargin))[]
if !isnothing(lims)
if !validate_limits_for_scale(lims, scale)
error("Found invalid $(dimsym)-limits $lims for scale $(scale) which is defined on the interval $(defined_interval(scale))")
end
lims = expandlimits(lims, margin[1], margin[2], scale)
end
# if no limits have been found, use the targetlimits directly
if isnothing(lims)
lims = limits(ax.targetlimits[], dim)
end
return lims
end
xautolimits(ax::Axis) = autolimits(ax, 1)
yautolimits(ax::Axis) = autolimits(ax, 2)
"""
linkaxes!(a::Axis, others...)
Link both x and y axes of all given `Axis` so that they stay synchronized.
"""
function linkaxes!(a::Axis, others...)
linkxaxes!(a, others...)
linkyaxes!(a, others...)
end
function adjustlimits!(la)
asp = la.autolimitaspect[]
target = la.targetlimits[]
area = la.scene.px_area[]
# in the simplest case, just update the final limits with the target limits