-
-
Notifications
You must be signed in to change notification settings - Fork 356
/
gr.jl
2119 lines (1911 loc) · 71.1 KB
/
gr.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
# https://github.com/jheinen/GR.jl - significant contributions by @jheinen
const gr_projections = (auto = 1, ortho = 1, orthographic = 1, persp = 2, perspective = 2)
const gr_linetypes = (auto = 1, solid = 1, dash = 2, dot = 3, dashdot = 4, dashdotdot = -1)
const gr_fill_styles = ((/) = 9, (\) = 10, (|) = 7, (-) = 8, (+) = 11, (x) = 6)
const gr_x_log_scales =
(ln = GR.OPTION_X_LN, log2 = GR.OPTION_X_LOG2, log10 = GR.OPTION_X_LOG)
const gr_y_log_scales =
(ln = GR.OPTION_Y_LN, log2 = GR.OPTION_Y_LOG2, log10 = GR.OPTION_Y_LOG)
const gr_z_log_scales =
(ln = GR.OPTION_Z_LN, log2 = GR.OPTION_Z_LOG2, log10 = GR.OPTION_Z_LOG)
const gr_arrowstyles = (
simple = 1,
hollow = 3,
filled = 4,
triangle = 5,
filledtriangle = 6,
closed = 6,
open = 5,
)
const gr_markertypes = (
auto = 1,
pixel = 1,
none = -1,
circle = -1,
rect = -7,
diamond = -13,
utriangle = -3,
dtriangle = -5,
ltriangle = -18,
rtriangle = -17,
pentagon = -21,
hexagon = -22,
heptagon = -23,
octagon = -24,
cross = 2,
xcross = 5,
(+) = 2,
x = 5,
star4 = -25,
star5 = -26,
star6 = -27,
star7 = -28,
star8 = -29,
vline = -30,
hline = -31,
)
const gr_haligns = (
left = GR.TEXT_HALIGN_LEFT,
hcenter = GR.TEXT_HALIGN_CENTER,
center = GR.TEXT_HALIGN_CENTER,
right = GR.TEXT_HALIGN_RIGHT,
)
const gr_valigns = (
top = GR.TEXT_VALIGN_TOP,
vcenter = GR.TEXT_VALIGN_HALF,
center = GR.TEXT_VALIGN_HALF,
bottom = GR.TEXT_VALIGN_BOTTOM,
)
const gr_font_family = Dict(
# compat
"times" => 101,
"helvetica" => 105,
"courier" => 109,
"bookman" => 114,
"newcenturyschlbk" => 118,
"avantgarde" => 122,
"palatino" => 126,
"serif-roman" => 232,
"sans-serif" => 233,
# https://gr-framework.org/fonts.html
"times roman" => 101,
"times italic" => 102,
"times bold" => 103,
"times bold italic" => 104,
"helvetica" => 105,
"helvetica oblique" => 106,
"helvetica bold" => 107,
"helvetica bold oblique" => 108,
"courier" => 109,
"courier oblique" => 110,
"courier bold" => 111,
"courier bold oblique" => 112,
"symbol" => 113,
"bookman light" => 114,
"bookman light italic" => 115,
"bookman demi" => 116,
"bookman demi italic" => 117,
"new century schoolbook roman" => 118,
"new century schoolbook italic" => 119,
"new century schoolbook bold" => 120,
"new century schoolbook bold italic" => 121,
"avantgarde book" => 122,
"avantgarde book oblique" => 123,
"avantgarde demi" => 124,
"avantgarde demi oblique" => 125,
"palatino roman" => 126,
"palatino italic" => 127,
"palatino bold" => 128,
"palatino bold italic" => 129,
"zapf chancery medium italic" => 130,
"zapf dingbats" => 131,
"computer modern" => 232,
"dejavu sans" => 233,
)
mutable struct GRViewport{T}
xmin::T
xmax::T
ymin::T
ymax::T
end
width(vp::GRViewport) = vp.xmax - vp.xmin
height(vp::GRViewport) = vp.ymax - vp.ymin
xcenter(vp::GRViewport) = 0.5(vp.xmin + vp.xmax)
ycenter(vp::GRViewport) = 0.5(vp.ymin + vp.ymax)
xposition(vp::GRViewport, pos) = vp.xmin + pos * width(vp)
yposition(vp::GRViewport, pos) = vp.ymin + pos * height(vp)
# --------------------------------------------------------------------------------------
gr_is3d(st) = RecipesPipeline.is3d(st)
gr_color(c, ::Type) = gr_color(RGBA(c), RGB)
gr_color(c) = gr_color(c, color_type(c))
gr_color(c, ::Type{<:AbstractRGB}) = UInt32(
round(UInt, clamp(255alpha(c), 0, 255)) << 24 +
round(UInt, clamp(255blue(c), 0, 255)) << 16 +
round(UInt, clamp(255green(c), 0, 255)) << 8 +
round(UInt, clamp(255red(c), 0, 255)),
)
gr_color(c, ::Type{<:AbstractGray}) =
let g = round(UInt, clamp(255gray(c), 0, 255)),
α = round(UInt, clamp(255alpha(c), 0, 255))
UInt32(α << 24 + g << 16 + g << 8 + g)
end
set_RGBA_alpha(alpha, c::RGBA) = RGBA(red(c), green(c), blue(c), alpha)
set_RGBA_alpha(alpha::Nothing, c::RGBA) = c
function gr_getcolorind(c)
gr_set_transparency(float(alpha(c)))
convert(Int, GR.inqcolorfromrgb(red(c), green(c), blue(c)))
end
gr_set_linecolor(c) = GR.setlinecolorind(gr_getcolorind(_cycle(c, 1)))
gr_set_fillcolor(c) = GR.setfillcolorind(gr_getcolorind(_cycle(c, 1)))
gr_set_markercolor(c) = GR.setmarkercolorind(gr_getcolorind(_cycle(c, 1)))
gr_set_bordercolor(c) = GR.setbordercolorind(gr_getcolorind(_cycle(c, 1)))
gr_set_textcolor(c) = GR.settextcolorind(gr_getcolorind(_cycle(c, 1)))
gr_set_transparency(α::Real) = GR.settransparency(clamp(α, 0, 1))
gr_set_transparency(::Nothing) = GR.settransparency(1)
gr_set_transparency(c, α) = gr_set_transparency(α)
gr_set_transparency(c::Colorant, ::Nothing) = gr_set_transparency(c)
gr_set_transparency(c::Colorant) = GR.settransparency(alpha(c))
gr_set_arrowstyle(style::Symbol) = GR.setarrowstyle(get(gr_arrowstyles, style, 1))
gr_set_fillstyle(::Nothing) = GR.setfillintstyle(GR.INTSTYLE_SOLID)
function gr_set_fillstyle(s::Symbol)
GR.setfillintstyle(GR.INTSTYLE_HATCH)
GR.setfillstyle(get(gr_fill_styles, s, 9))
nothing
end
# https://gr-framework.org/python-gr.html?highlight=setprojectiontype#gr.setprojectiontype
# PROJECTION_DEFAULT 0 default
# PROJECTION_ORTHOGRAPHIC 1 orthographic
# PROJECTION_PERSPECTIVE 2 perspective
# we choose to unify backends by using a default `orthographic` proj when `:auto`
gr_set_projectiontype(sp) = GR.setprojectiontype(gr_projections[sp[:projection_type]])
# --------------------------------------------------------------------------------------
# draw line segments, splitting x/y into contiguous/finite segments
# note: this can be used for shapes by passing func `GR.fillarea`
function gr_polyline(x, y, func = GR.polyline; arrowside = :none, arrowstyle = :simple)
draw_head = arrowside in (:head, :both)
draw_tail = arrowside in (:tail, :both)
n = length(x)
iend = 0
while iend < n - 1
istart = -1 # set istart to the first index that is finite
for j in (iend + 1):n
if ok(x[j], y[j])
istart = j
break
end
end
if istart > 0
iend = -1 # iend is the last finite index
for j in (istart + 1):n
if ok(x[j], y[j])
iend = j
else
break
end
end
end
# if we found a start and end, draw the line segment, otherwise we're done
if istart > 0 && iend > 0
func(x[istart:iend], y[istart:iend])
if draw_head
gr_set_arrowstyle(arrowstyle)
GR.drawarrow(x[iend - 1], y[iend - 1], x[iend], y[iend])
end
if draw_tail
gr_set_arrowstyle(arrowstyle)
GR.drawarrow(x[istart + 1], y[istart + 1], x[istart], y[istart])
end
else
break
end
end
end
function gr_polyline3d(x, y, z, func = GR.polyline3d)
iend = 0
n = length(x)
while iend < n - 1
istart = -1 # set istart to the first index that is finite
for j in (iend + 1):n
if ok(x[j], y[j], z[j])
istart = j
break
end
end
if istart > 0
iend = -1 # iend is the last finite index
for j in (istart + 1):n
if ok(x[j], y[j], z[j])
iend = j
else
break
end
end
end
# if we found a start and end, draw the line segment, otherwise we're done
if istart > 0 && iend > 0
func(x[istart:iend], y[istart:iend], z[istart:iend])
else
break
end
end
end
gr_inqtext(x, y, s) = gr_inqtext(x, y, string(s))
gr_inqtext(x, y, s::AbstractString) =
if (occursin('\\', s) || occursin(r"10\^{|2\^{|e\^{", s)) &&
match(r".*\$[^\$]+?\$.*", String(s)) === nothing
GR.inqtextext(x, y, s)
else
GR.inqtext(x, y, s)
end
gr_text(x, y, s) = gr_text(x, y, string(s))
gr_text(x, y, s::AbstractString) =
if (occursin('\\', s) || occursin(r"10\^{|2\^{|e\^{", s)) &&
match(r".*\$[^\$]+?\$.*", String(s)) === nothing
GR.textext(x, y, s)
else
GR.text(x, y, s)
end
function gr_polaraxes(rmin::Real, rmax::Real, sp::Subplot)
GR.savestate()
xaxis = sp[:xaxis]
yaxis = sp[:yaxis]
α = 0:45:315
a = α .+ 90
sinf = sind.(a)
cosf = cosd.(a)
rtick_values, rtick_labels = get_ticks(sp, yaxis, update = false)
# draw angular grid
if xaxis[:grid]
gr_set_line(
xaxis[:gridlinewidth],
xaxis[:gridstyle],
xaxis[:foreground_color_grid],
sp,
)
gr_set_transparency(xaxis[:foreground_color_grid], xaxis[:gridalpha])
for i in eachindex(α)
GR.polyline([sinf[i], 0], [cosf[i], 0])
end
end
# draw radial grid
if yaxis[:grid]
gr_set_line(
yaxis[:gridlinewidth],
yaxis[:gridstyle],
yaxis[:foreground_color_grid],
sp,
)
gr_set_transparency(yaxis[:foreground_color_grid], yaxis[:gridalpha])
for i in eachindex(rtick_values)
r = (rtick_values[i] - rmin) / (rmax - rmin)
(r ≤ 1 && r ≥ 0) && GR.drawarc(-r, r, -r, r, 0, 359)
end
GR.drawarc(-1, 1, -1, 1, 0, 359)
end
# prepare to draw ticks
gr_set_transparency(1)
GR.setlinecolorind(90)
GR.settextalign(GR.TEXT_HALIGN_CENTER, GR.TEXT_VALIGN_HALF)
# draw angular ticks
if xaxis[:showaxis]
GR.drawarc(-1, 1, -1, 1, 0, 359)
for i in eachindex(α)
x, y = GR.wctondc(1.1sinf[i], 1.1cosf[i])
GR.textext(x, y, string((360 - α[i]) % 360, "^o"))
end
end
# draw radial ticks
yaxis[:showaxis] && for i in eachindex(rtick_values)
r = (rtick_values[i] - rmin) / (rmax - rmin)
(r ≤ 1 && r ≥ 0) && gr_text(GR.wctondc(0.05, r)..., _cycle(rtick_labels, i))
end
GR.restorestate()
nothing
end
# using the axis extrema and limit overrides, return the min/max value for this axis
gr_x_axislims(sp::Subplot) = axis_limits(sp, :x)
gr_y_axislims(sp::Subplot) = axis_limits(sp, :y)
gr_z_axislims(sp::Subplot) = axis_limits(sp, :z)
gr_xy_axislims(sp::Subplot) = gr_x_axislims(sp)..., gr_y_axislims(sp)...
function gr_fill_viewport(vp::GRViewport, c)
if alpha(c) == 0
return nothing
end
GR.savestate()
GR.selntran(0)
GR.setscale(0)
GR.setfillintstyle(GR.INTSTYLE_SOLID)
gr_set_fillcolor(c)
GR.fillrect(vp.xmin, vp.xmax, vp.ymin, vp.ymax)
GR.selntran(1)
GR.restorestate()
nothing
end
gr_fill_plotarea(sp, vp::GRViewport) =
gr_is3d(sp) || gr_fill_viewport(vp, plot_color(sp[:background_color_inside]))
# ---------------------------------------------------------
gr_nominal_size(s) = minimum(get_size(s)) / 500
# draw ONE Shape
function gr_draw_marker(series, xi, yi, zi, clims, i, msize, strokewidth, shape::Shape)
# convert to ndc coords (percentages of window) ...
xi, yi = if zi === nothing
GR.wctondc(xi, yi)
else
gr_w3tondc(xi, yi, zi)
end
f = msize / sum(get_size(series))
# ... convert back to world coordinates
sx, sy = coords(shape)
xs_ys = GR.ndctowc.(xi .+ sx .* f, yi .+ sy .* f)
xs, ys = getindex.(xs_ys, 1), getindex.(xs_ys, 2)
# draw the interior
mc = get_markercolor(series, clims, i)
gr_set_fill(mc)
gr_set_transparency(mc, get_markeralpha(series, i))
GR.fillarea(xs, ys)
# draw the shapes
msc = get_markerstrokecolor(series, i)
gr_set_line(strokewidth, :solid, msc, series)
gr_set_transparency(msc, get_markerstrokealpha(series, i))
GR.polyline(xs, ys)
nothing
end
# draw ONE symbol marker
function gr_draw_marker(series, xi, yi, zi, clims, i, msize, strokewidth, shape::Symbol)
GR.setborderwidth(strokewidth)
gr_set_bordercolor(get_markerstrokecolor(series, i))
gr_set_markercolor(get_markercolor(series, clims, i))
gr_set_transparency(get_markeralpha(series, i))
GR.setmarkertype(gr_markertypes[shape])
GR.setmarkersize(0.3msize / gr_nominal_size(series))
if zi === nothing
GR.polymarker([xi], [yi])
else
GR.polymarker3d([xi], [yi], [zi])
end
nothing
end
# ---------------------------------------------------------
function gr_set_line(lw, style, c, s) # s can be Subplot or Series
GR.setlinetype(gr_linetypes[style])
GR.setlinewidth(get_thickness_scaling(s) * max(0, lw / gr_nominal_size(s)))
gr_set_linecolor(c)
nothing
end
gr_set_fill(c) = (gr_set_fillcolor(c); GR.setfillintstyle(GR.INTSTYLE_SOLID); nothing)
# this stores the conversion from a font pointsize to "percentage of window height"
# (which is what GR uses). `s` can be a Series, Subplot or Plot
gr_point_mult(s) = 1.5get_thickness_scaling(s) * px / pt / maximum(get_size(s))
# set the font attributes.
function gr_set_font(
f::Font,
s;
halign = f.halign,
valign = f.valign,
color = f.color,
rotation = f.rotation,
)
family = lowercase(f.family)
GR.setcharheight(gr_point_mult(s) * f.pointsize)
GR.setcharup(sincosd(-rotation)...)
if !haskey(gr_font_family, family)
gr_font_family[family] = GR.loadfont(string(f.family, ".ttf"))
end
haskey(gr_font_family, family) && GR.settextfontprec(
gr_font_family[family],
gr_font_family[family] ≥ 200 ? 3 : GR.TEXT_PRECISION_STRING,
)
gr_set_textcolor(plot_color(color))
GR.settextalign(gr_haligns[halign], gr_valigns[valign])
nothing
end
function gr_w3tondc(x, y, z)
xw, yw, _ = GR.wc3towc(x, y, z)
GR.wctondc(xw, yw) # x, y
end
# --------------------------------------------------------------------------------------
# viewport plot area
function gr_viewport_from_bbox(sp::Subplot{GRBackend}, bb::BoundingBox, w, h, vp_canvas)
viewport = GRViewport(
vp_canvas.xmax * (left(bb) / w),
vp_canvas.xmax * (right(bb) / w),
vp_canvas.ymax * (1 - bottom(bb) / h),
vp_canvas.ymax * (1 - top(bb) / h),
)
hascolorbar(sp) && (viewport.xmax -= 0.1(1 + 0.5gr_is3d(sp)))
viewport
end
# change so we're focused on the viewport area
# in case someone wants to modify these hardcoded factors
const gr_cbar_width = Ref(0.03)
const gr_cbar_offsets = Ref((0.02, 0.07))
function gr_set_viewport_cmap(sp::Subplot, vp::GRViewport)
offset = gr_cbar_offsets[][gr_is3d(sp) ? 2 : 1]
args = vp.xmax + offset, vp.xmax + offset + gr_cbar_width[], vp.ymin, vp.ymax
GR.setviewport(args...)
GRViewport(args...)
end
function gr_set_viewport_polar(vp)
x_ctr = xcenter(vp)
dist = vp.ymax - 0.05width(vp)
y_ctr = 0.5(vp.ymin + dist)
r = 0.5NaNMath.min(width(vp), dist - vp.ymin)
GR.setviewport(x_ctr - r, x_ctr + r, y_ctr - r, y_ctr + r)
GR.setwindow(-1, 1, -1, 1)
r
end
struct GRColorbar
gradients
fills
lines
GRColorbar() = new([], [], [])
end
function gr_update_colorbar!(cbar::GRColorbar, series::Series)
(style = colorbar_style(series)) === nothing && return
list =
style == cbar_gradient ? cbar.gradients :
style == cbar_fill ? cbar.fills :
style == cbar_lines ? cbar.lines : error("Unknown colorbar style: $style.")
push!(list, series)
end
function gr_contour_levels(series::Series, clims)
levels = collect(contour_levels(series, clims))
# GR implicitly uses the maximal z value as the highest level
isfilledcontour(series) && pop!(levels)
levels
end
function gr_colorbar_colors(series::Series, clims)
colors = if iscontour(series)
levels = gr_contour_levels(series, clims)
zrange = if isfilledcontour(series)
ignorenan_extrema(levels) # GR.contourf uses a color range according to supplied levels
else
clims # GR.contour uses a color range according to data range
end
@. 1_000 + 255 * (levels - zrange[1]) / (zrange[2] - zrange[1])
else
1_000:1_255 # 256 values
end
round.(Int, colors)
end
function _cbar_unique(values, propname)
out = last(values)
if any(x != out for x in values)
@warn """
Multiple series with different $propname share a colorbar.
Colorbar may not reflect all series correctly.
"""
end
out
end
const gr_colorbar_tick_size = Ref(0.005)
function gr_colorbar_title(sp::Subplot)
title = if (ttl = sp[:colorbar_title]) isa PlotText
ttl
else
text(ttl, colorbartitlefont(sp))
end
title.font.rotation += 90 # default rotated by 90° (vertical)
title
end
function gr_colorbar_info(sp::Subplot)
clims = gr_clims(sp)
maximum(first.(gr_text_size.(clims))), clims
end
# add the colorbar
function gr_draw_colorbar(cbar::GRColorbar, sp::Subplot, vp::GRViewport)
GR.savestate()
x_min, x_max = gr_x_axislims(sp)
tick_max_width, clims = gr_colorbar_info(sp)
z_min, z_max = clims
vp_cmap = gr_set_viewport_cmap(sp, vp)
GR.setscale(0)
GR.setwindow(x_min, x_max, z_min, z_max)
if !isempty(cbar.gradients)
series = cbar.gradients
gr_set_gradient(_cbar_unique(get_colorgradient.(series), "color"))
gr_set_transparency(_cbar_unique(get_fillalpha.(series), "fill alpha"))
GR.cellarray(x_min, x_max, z_max, z_min, 1, 256, 1_000:1_255)
end
if !isempty(cbar.fills)
series = cbar.fills
GR.setfillintstyle(GR.INTSTYLE_SOLID)
gr_set_gradient(_cbar_unique(get_colorgradient.(series), "color"))
gr_set_transparency(_cbar_unique(get_fillalpha.(series), "fill alpha"))
levels = _cbar_unique(contour_levels.(series, Ref(clims)), "levels")
# GR implicitly uses the maximal z value as the highest level
if last(levels) < z_max
@warn "GR: highest contour level less than maximal z value is not supported."
# replace levels, rather than assign to last(levels), to ensure type
# promotion in case levels is an integer array
pop!(levels)
push!(levels, z_max)
end
colors = gr_colorbar_colors(last(series), clims)
for (from, to, color) in zip(levels[1:(end - 1)], levels[2:end], colors)
GR.setfillcolorind(color)
GR.fillrect(x_min, x_max, from, to)
end
end
if !isempty(cbar.lines)
series = cbar.lines
gr_set_gradient(_cbar_unique(get_colorgradient.(series), "color"))
gr_set_line(
_cbar_unique(get_linewidth.(series), "line width"),
_cbar_unique(get_linestyle.(series), "line style"),
_cbar_unique(get_linecolor.(series, Ref(clims)), "line color"),
sp,
)
gr_set_transparency(_cbar_unique(get_linealpha.(series), "line alpha"))
levels = _cbar_unique(contour_levels.(series, Ref(clims)), "levels")
colors = gr_colorbar_colors(last(series), clims)
for (line, color) in zip(levels, colors)
GR.setlinecolorind(color)
GR.polyline([x_min, x_max], [line, line])
end
end
if _has_ticks(sp[:colorbar_ticks])
z_tick = 0.5GR.tick(z_min, z_max)
gr_set_line(1, :solid, plot_color(:black), sp)
(yscale = sp[:colorbar_scale]) ∈ _logScales && GR.setscale(gr_y_log_scales[yscale])
# signature: gr.axes(x_tick, y_tick, x_org, y_org, major_x, major_y, tick_size)
GR.axes(0, z_tick, x_max, z_min, 0, 1, gr_colorbar_tick_size[])
end
title = gr_colorbar_title(sp)
gr_set_font(title.font, sp; halign = :center, valign = :top)
gr_text(vp.xmax + 0.1, ycenter(vp), title.str)
GR.restorestate()
nothing
end
position(symb) =
if symb === :top || symb === :right
0.95
elseif symb === :left || symb === :bottom
0.05
else
0.5
end
alignment(symb) =
if symb === :top || symb === :right
:right
elseif symb === :left || symb === :bottom
:left
else
:center
end
# --------------------------------------------------------------------------------------
function gr_set_gradient(c)
grad = _as_gradient(c)
for (i, z) in enumerate(range(0, 1; length = 256))
c = grad[z]
GR.setcolorrep(999 + i, red(c), green(c), blue(c))
end
grad
end
gr_set_gradient(series::Series) =
(color = get_colorgradient(series)) !== nothing && gr_set_gradient(color)
# this is our new display func... set up the viewport_canvas, compute bounding boxes, and display each subplot
function gr_display(plt::Plot, dpi_factor = 1)
GR.clearws()
# collect some monitor/display sizes in meters and pixels
dsp_width_meters, dsp_height_meters, dsp_width_px, dsp_height_px = GR.inqdspsize()
dsp_width_ratio = dsp_width_meters / dsp_width_px
dsp_height_ratio = dsp_height_meters / dsp_height_px
# compute the viewport_canvas, normalized to the larger dimension
vp_canvas = GRViewport(0.0, 1.0, 0.0, 1.0)
w, h = get_size(plt)
if w > h
ratio = float(h) / w
msize = dsp_width_ratio * w * dpi_factor
GR.setwsviewport(0, msize, 0, msize * ratio)
GR.setwswindow(0, 1, 0, ratio)
vp_canvas.ymin *= ratio
vp_canvas.ymax *= ratio
else
ratio = float(w) / h
msize = dsp_height_ratio * h * dpi_factor
GR.setwsviewport(0, msize * ratio, 0, msize)
GR.setwswindow(0, ratio, 0, 1)
vp_canvas.xmin *= ratio
vp_canvas.xmax *= ratio
end
# fill in the viewport_canvas background
gr_fill_viewport(vp_canvas, plt[:background_color_outside])
# subplots
foreach(sp -> gr_display(sp, w * px, h * px, vp_canvas), plt.subplots)
GR.updatews()
nothing
end
gr_set_tickfont(sp, ax::Axis; kw...) = gr_set_font(
tickfont(ax),
sp;
rotation = ax[:rotation],
color = ax[:tickfontcolor],
kw...,
)
function gr_set_tickfont(sp, letter::Symbol; kw...)
axis = sp[get_attr_symbol(letter, :axis)]
gr_set_font(
tickfont(axis),
sp;
rotation = axis[:rotation],
color = axis[:tickfontcolor],
kw...,
)
end
# size of the text with no rotation
function gr_text_size(str)
GR.savestate()
GR.selntran(0)
GR.setcharup(0, 1)
(l, r), (b, t) = extrema.(gr_inqtext(0, 0, string(str)))
GR.restorestate()
r - l, t - b # w, h
end
# size of the text with rotation applied
function gr_text_size(str, rot)
GR.savestate()
GR.selntran(0)
GR.setcharup(0, 1)
(l, r), (b, t) = extrema.(gr_inqtext(0, 0, string(str)))
GR.restorestate()
text_box_width(r - l, t - b, rot), text_box_height(r - l, t - b, rot) # w, h
end
text_box_width(w, h, rot) = abs(cosd(rot)) * w + abs(cosd(rot + 90)) * h
text_box_height(w, h, rot) = abs(sind(rot)) * w + abs(sind(rot + 90)) * h
function gr_get_3d_axis_angle(cvs, nt, ft, letter)
length(cvs) < 2 && return 0
tickpoints = map(cv -> gr_w3tondc(sort_3d_axes(cv, nt, ft, letter)...), cvs)
dx = tickpoints[2][1] - tickpoints[1][1]
dy = tickpoints[2][2] - tickpoints[1][2]
atand(dy, dx)
end
function gr_get_ticks_size(ticks, rot)
w, h = 0.0, 0.0
for (cv, dv) in zip(ticks...)
wi, hi = gr_text_size(dv, rot)
w = NaNMath.max(w, wi)
h = NaNMath.max(h, hi)
end
w, h
end
function labelfunc(scale::Symbol, backend::GRBackend)
texfunc = labelfunc_tex(scale)
# replace dash with \minus (U+2212)
label -> replace(texfunc(label), "-" => "−")
end
function gr_axis_height(sp, axis)
GR.savestate()
ticks = get_ticks(sp, axis, update = false)
gr_set_font(tickfont(axis), sp)
h = (
ticks in (nothing, false, :none) ? 0 :
last(gr_get_ticks_size(ticks, axis[:rotation]))
)
if (guide = axis[:guide]) != ""
gr_set_font(guidefont(axis), sp)
h += last(gr_text_size(guide))
end
GR.restorestate()
h
end
function gr_axis_width(sp, axis)
GR.savestate()
ticks = get_ticks(sp, axis, update = false)
gr_set_font(tickfont(axis), sp)
w = (
ticks in (nothing, false, :none) ? 0 :
first(gr_get_ticks_size(ticks, axis[:rotation]))
)
if (guide = axis[:guide]) != ""
gr_set_font(guidefont(axis), sp)
w += last(gr_text_size(guide))
end
GR.restorestate()
w
end
function _update_min_padding!(sp::Subplot{GRBackend})
dpi = sp.plt[:thickness_scaling]
width, height = sp_size = get_size(sp)
# Add margin given by the user
padding = (
left = Ref(2mm + sp[:left_margin]),
top = Ref(2mm + sp[:top_margin]),
right = Ref(2mm + sp[:right_margin]),
bottom = Ref(2mm + sp[:bottom_margin]),
)
# Add margin for title
if (title = sp[:title]) != ""
gr_set_font(titlefont(sp), sp)
l = last(gr_text_size(title))
padding.top[] += 1mm + height * l * px
end
xaxis, yaxis, zaxis = axes = sp[:xaxis], sp[:yaxis], sp[:zaxis]
xticks, yticks, zticks = get_ticks.(Ref(sp), axes)
if gr_is3d(sp)
# Add margin for x and y ticks
m = 0mm
for (ax, tc) in ((xaxis, xticks), (yaxis, yticks))
isempty(first(tc)) && continue
rot = ax[:rotation]
gr_set_tickfont(
sp,
ax;
halign = (:left, :hcenter, :right)[sign(rot) + 2],
valign = ax[:mirror] ? :bottom : :top,
)
l = 0.01 + last(gr_get_ticks_size(tc, rot))
m = max(m, 1mm + height * l * px)
end
if m > 0mm
(xaxis[:mirror] || yaxis[:mirror]) && (padding.top[] += m)
(!xaxis[:mirror] || !yaxis[:mirror]) && (padding.bottom[] += m)
end
if !isempty(first(zticks))
rot = zaxis[:rotation]
gr_set_tickfont(
sp,
zaxis;
halign = zaxis[:mirror] ? :left : :right,
valign = (:top, :vcenter, :bottom)[sign(rot) + 2],
)
l = 0.01 + first(gr_get_ticks_size(zticks, rot))
padding[zaxis[:mirror] ? :right : :left][] += 1mm + width * l * px
end
# Add margin for x or y label
m = 0mm
for ax in (xaxis, yaxis)
(guide = ax[:guide] == "") && continue
gr_set_font(guidefont(ax), sp)
l = last(gr_text_size(guide))
m = max(m, 1mm + height * l * px)
end
if m > 0mm
# NOTE: `xaxis` arbitrary here ?
padding[mirrored(xaxis, :top) ? :top : :bottom][] += m
end
# Add margin for z label
if (guide = zaxis[:guide]) != ""
gr_set_font(guidefont(zaxis), sp)
l = last(gr_text_size(guide))
padding[mirrored(zaxis, :right) ? :right : :left][] += 1mm + height * l * px # NOTE: why `height` here ?
end
else
# Add margin for x/y ticks & labels
for (ax, tc, (a, b)) in
((xaxis, xticks, (:top, :bottom)), (yaxis, yticks, (:right, :left)))
if !isempty(first(tc))
isy = ax[:letter] === :y
gr_set_tickfont(sp, ax)
ts = gr_get_ticks_size(tc, ax[:rotation])
l = 0.01 + (isy ? first(ts) : last(ts))
padding[ax[:mirror] ? a : b][] += 1mm + sp_size[isy ? 1 : 2] * l * px
end
if (guide = ax[:guide]) != ""
gr_set_font(guidefont(ax), sp)
l = last(gr_text_size(guide))
padding[mirrored(ax, a) ? a : b][] += 1mm + height * l * px # NOTE: using `height` is arbitrary
end
end
end
if (title = gr_colorbar_title(sp)).str != ""
padding.right[] += @static if false
sz = gr_text_size(title)
l = is_horizontal(title) ? first(sz) : last(sz)
l * width * px
else
4mm
end
end
sp.minpad = (
dpi * padding.left[],
dpi * padding.top[],
dpi * padding.right[],
dpi * padding.bottom[],
)
end
remap(x, lo, hi) = (x - lo) / (hi - lo)
get_z_normalized(z, clims...) = isnan(z) ? 256 / 255 : remap(clamp(z, clims...), clims...)
function gr_clims(sp, args...)
sp[:clims] === :auto || return get_clims(sp)
lo, hi = get_clims(sp, args...)
if lo == hi
if lo == 0
hi = one(hi)
elseif lo < 0
hi = zero(hi)
else
lo = zero(lo)
end
end
lo, hi
end
function gr_viewport_bbox(vp, sp, color)
GR.savestate()
GR.selntran(0)
GR.setscale(0)
gr_set_line(1, :solid, plot_color(color), sp)
GR.drawrect(vp.xmin, vp.xmax, vp.ymin, vp.ymax)
GR.selntran(1)
GR.restorestate()
nothing
end
function gr_display(sp::Subplot{GRBackend}, w, h, vp_canvas::GRViewport)
_update_min_padding!(sp)
# the viewports for this subplot and the whole plot
vp_sp = gr_viewport_from_bbox(sp, bbox(sp), w, h, vp_canvas)
vp_plt = gr_viewport_from_bbox(sp, plotarea(sp), w, h, vp_canvas)
# update plot viewport
leg = gr_get_legend_geometry(vp_plt, sp)
gr_update_viewport_legend!(vp_plt, sp, leg)
gr_update_viewport_ratio!(vp_plt, sp)
# fill in the plot area background
gr_fill_plotarea(sp, vp_plt)
# set our plot area view
GR.setviewport(vp_plt.xmin, vp_plt.xmax, vp_plt.ymin, vp_plt.ymax)
# set the scale flags and window
gr_set_window(sp, vp_plt)
# draw the axes
gr_draw_axes(sp, vp_plt)
gr_add_title(sp, vp_plt, vp_sp)
_debug[] && gr_viewport_bbox(vp_sp, sp, :red)
_debug[] && gr_viewport_bbox(vp_plt, sp, :green)
# this needs to be here to point the colormap to the right indices
GR.setcolormap(1_000 + GR.COLORMAP_COOLWARM)
# init the colorbar
cbar = GRColorbar()
for series in series_list(sp)
gr_add_series(sp, series)
gr_update_colorbar!(cbar, series)
end
# draw the colorbar
hascolorbar(sp) && gr_draw_colorbar(cbar, sp, vp_plt)
# add the legend
gr_add_legend(sp, leg, vp_plt)
# add annotations
for ann in sp[:annotations]
x, y = if is3d(sp)
x, y, z, val = locate_annotation(sp, ann...)
GR.setwindow(-1, 1, -1, 1)
gr_w3tondc(x, y, z)
else
x, y, val = locate_annotation(sp, ann...)
GR.wctondc(x, y)
end
gr_set_font(val.font, sp)
gr_text(x, y, val.str)
end
end
## Legend
gr_legend_bbox(xpos, ypos, leg) = GR.drawrect(
xpos - leg.space - leg.span, # see ref(1)
xpos + leg.textw,
ypos - 0.5leg.dy,
ypos + 0.5leg.dy,
)
const gr_lw_clamp_factor = Ref(5)
function gr_add_legend(sp, leg, viewport_area)