-
-
Notifications
You must be signed in to change notification settings - Fork 354
/
pgfplotsx.jl
1339 lines (1249 loc) · 49.8 KB
/
pgfplotsx.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
import .PGFPlotsX: Options, Table
import LaTeXStrings: LaTeXString
import UUIDs: uuid4
import Latexify
import Contour
Base.@kwdef mutable struct PGFPlotsXPlot
is_created::Bool = false
was_shown::Bool = false
the_plot::PGFPlotsX.TikzDocument = PGFPlotsX.TikzDocument()
function PGFPlotsXPlot(is_created, was_shown, the_plot)
pgfx_plot = new(is_created, was_shown, the_plot)
# tikz libraries
PGFPlotsX.push_preamble!(pgfx_plot.the_plot, "\\usetikzlibrary{arrows.meta}")
PGFPlotsX.push_preamble!(pgfx_plot.the_plot, "\\usetikzlibrary{backgrounds}")
# pgfplots libraries
PGFPlotsX.push_preamble!(pgfx_plot.the_plot, "\\usepgfplotslibrary{patchplots}")
PGFPlotsX.push_preamble!(pgfx_plot.the_plot, "\\usepgfplotslibrary{fillbetween}")
# compatibility fixes
# add background layer to standard layers
PGFPlotsX.push_preamble!(
pgfx_plot.the_plot,
raw"""\pgfplotsset{%
layers/standard/.define layer set={%
background,axis background,axis grid,axis ticks,axis lines,axis tick labels,pre main,main,axis descriptions,axis foreground%
}{
grid style={/pgfplots/on layer=axis grid},%
tick style={/pgfplots/on layer=axis ticks},%
axis line style={/pgfplots/on layer=axis lines},%
label style={/pgfplots/on layer=axis descriptions},%
legend style={/pgfplots/on layer=axis descriptions},%
title style={/pgfplots/on layer=axis descriptions},%
colorbar style={/pgfplots/on layer=axis descriptions},%
ticklabel style={/pgfplots/on layer=axis tick labels},%
axis background@ style={/pgfplots/on layer=axis background},%
3d box foreground style={/pgfplots/on layer=axis foreground},%
},
}
""",
)
pgfx_plot
end
end
## end user utility functions
pgfx_axes(pgfx_plot::PGFPlotsXPlot) = pgfx_plot.the_plot.elements[1].elements
pgfx_preamble() = pgfx_preamble(current())
function pgfx_preamble(pgfx_plot::Plot{PGFPlotsXBackend})
old_flag = pgfx_plot.attr[:tex_output_standalone]
pgfx_plot.attr[:tex_output_standalone] = true
fulltext = String(repr("application/x-tex", pgfx_plot))
preamble = fulltext[1:(first(findfirst("\\begin{document}", fulltext)) - 1)]
pgfx_plot.attr[:tex_output_standalone] = old_flag
preamble
end
function surface_to_vecs(x::AVec, y::AVec, s::Union{AMat,Surface})
a = Array(s)
xn = Vector{eltype(x)}(undef, length(a))
yn = Vector{eltype(y)}(undef, length(a))
zn = Vector{eltype(s)}(undef, length(a))
for (n, (i, j)) in enumerate(Tuple.(CartesianIndices(a)))
if length(x) == size(s, 1)
i, j = j, i
end
xn[n] = x[j]
yn[n] = y[i]
zn[n] = a[i, j]
end
return xn, yn, zn
end
surface_to_vecs(x::AVec, y::AVec, z::AVec) = x, y, z
Base.push!(pgfx_plot::PGFPlotsXPlot, item) = push!(pgfx_plot.the_plot, item)
pgfx_split_extra_kw(extra) =
(get(extra, :add, nothing), filter(x -> first(x) !== :add, extra))
curly(obj) = "{$(string(obj))}"
# anything other than `Function`, `:plain` or `:latex` should map to `:latex` formatter instead
latex_formatter(formatter::Symbol) = formatter in (:plain, :latex) ? formatter : :latex
latex_formatter(formatter::Function) = formatter
pgfx_halign(k) = (left = "left", hcenter = "center", center = "center", right = "right")[k]
function (pgfx_plot::PGFPlotsXPlot)(plt::Plot{PGFPlotsXBackend})
if !pgfx_plot.is_created || pgfx_plot.was_shown
pgfx_sanitize_plot!(plt)
# extract extra kwargs
extra_plot, extra_plot_opt = pgfx_split_extra_kw(plt[:extra_plot_kwargs])
the_plot = PGFPlotsX.TikzPicture(Options(extra_plot_opt...))
extra_plot !== nothing && push!(the_plot, wraptuple(extra_plot)...)
bgc = plt.attr[if plt.attr[:background_color_outside] === :match
:background_color
else
:background_color_outside
end]
if bgc isa Colors.Colorant
cstr = plot_color(bgc)
push!(
the_plot.options,
"/tikz/background rectangle/.style" => Options(
# "draw" => "black",
"fill" => cstr,
"draw opacity" => alpha(cstr),
),
"show background rectangle" => nothing,
)
end
for sp in plt.subplots
bb2 = bbox(sp)
dx, dy = bb2.x0
sp_w, sp_h = width(bb2), height(bb2)
if sp[:subplot_index] == plt[:plot_titleindex]
x = dx + sp_w / 2 - 10mm # FIXME: get rid of magic constant
y = dy + sp_h / 2
pgfx_add_annotation!(
the_plot,
x,
y,
PlotText(plt[:plot_title], plottitlefont(plt)),
pgfx_thickness_scaling(plt);
options = Options("anchor" => "center"),
cs = "",
)
continue
end
lpad = leftpad(sp) + sp[:left_margin]
rpad = rightpad(sp) + sp[:right_margin]
tpad = toppad(sp) + sp[:top_margin]
bpad = bottompad(sp) + sp[:bottom_margin]
dx += lpad
dy += tpad
title_cstr = plot_color(sp[:titlefontcolor])
bgc_inside = plot_color(sp[:background_color_inside])
update_clims(sp)
axis_opt = Options(
"point meta max" => get_clims(sp)[2],
"point meta min" => get_clims(sp)[1],
"legend cell align" => "left",
"legend columns" => pgfx_legend_col(sp[:legend_column]),
"title" => sp[:title],
"title style" => Options(
pgfx_get_title_pos(sp[:titlelocation])...,
"font" => pgfx_font(sp[:titlefontsize], pgfx_thickness_scaling(sp)),
"color" => title_cstr,
"draw opacity" => alpha(title_cstr),
"rotate" => sp[:titlefontrotation],
"align" => pgfx_halign(sp[:titlefonthalign]),
),
"legend style" => pgfx_get_legend_style(sp),
"axis background/.style" =>
Options("fill" => bgc_inside, "opacity" => alpha(bgc_inside)),
# these are for layouting
"anchor" => "north west",
"xshift" => string(dx),
"yshift" => string(-dy),
)
sp_w > 0mm && push!(axis_opt, "width" => string(sp_w - (rpad + lpad)))
sp_h > 0mm && push!(axis_opt, "height" => string(sp_h - (tpad + bpad)))
for letter in (:x, :y, :z)
if letter !== :z || RecipesPipeline.is3d(sp)
pgfx_axis!(axis_opt, sp, letter)
end
end
# Search series for any gradient. In case one series uses a gradient set the colorbar and colomap.
# The reasoning behind doing this on the axis level is that
# pgfplots colorbar seems to only work on axis level and needs the proper colormap for correctly displaying it.
# It's also possible to assign the colormap to the series itself but
# then the colormap needs to be added twice, once for the axis and once for the series.
# As it is likely that all series within the same axis use the same colormap this should not cause any problem.
for series in series_list(sp)
if hascolorbar(series)
cg = get_colorgradient(series)
cm = pgfx_colormap(cg)
PGFPlotsX.push_preamble!(
pgfx_plot.the_plot,
"\\pgfplotsset{\ncolormap={plots$(sp.attr[:subplot_index])}{$cm},\n}",
)
push!(axis_opt, "colormap name" => "plots$(sp.attr[:subplot_index])")
if cg isa PlotUtils.CategoricalColorGradient
push!(
axis_opt,
"colormap access" => "piecewise const",
"colorbar sampled" => nothing,
)
end
break
end
end
if hascolorbar(sp)
formatter = latex_formatter(sp[:colorbar_formatter])
cticks = curly(join(get_colorbar_ticks(sp; formatter = formatter)[1], ','))
colorbar_style = if sp[:colorbar] === :top
push!(
Options("xlabel" => sp[:colorbar_title]),
"xlabel style" => pgfx_get_colorbar_title_style(sp),
"at" => "(0.5, 1.05)",
"anchor" => "south",
"xtick" => cticks,
"xticklabel pos" => "upper",
"xticklabel style" => pgfx_get_colorbar_ticklabel_style(sp),
)
else
push!(
Options("ylabel" => sp[:colorbar_title]),
"ylabel style" => pgfx_get_colorbar_title_style(sp),
"ytick" => cticks,
"yticklabel style" => pgfx_get_colorbar_ticklabel_style(sp),
)
end
push!(
axis_opt,
"colorbar $(pgfx_get_colorbar_pos(sp[:colorbar]))" => nothing,
"colorbar style" => colorbar_style,
)
else
push!(axis_opt, "colorbar" => "false")
end
if RecipesPipeline.is3d(sp)
if (ar = sp[:aspect_ratio]) !== :auto
push!(
axis_opt,
"unit vector ratio" => ar === :equal ? 1 : join(ar, ' '),
)
end
push!(axis_opt, "view" => tuple(sp[:camera]))
end
axisf = if sp[:projection] === :polar
# push!(axis_opt, "xmin" => 90)
# push!(axis_opt, "xmax" => 450)
PGFPlotsX.PolarAxis
else
PGFPlotsX.Axis
end
extra_sp, extra_sp_opt = pgfx_split_extra_kw(sp[:extra_kwargs])
axis = axisf(merge(axis_opt, Options(extra_sp_opt...)))
extra_sp !== nothing && push!(axis, wraptuple(extra_sp)...)
if sp[:legend_title] !== nothing
legtfont = legendtitlefont(sp)
leg_opt = Options(
"font" => pgfx_font(legtfont.pointsize, pgfx_thickness_scaling(sp)),
"text" => legtfont.color,
)
push!(
axis,
Options("\\addlegendimage{empty legend}" => nothing),
PGFPlotsX.LegendEntry(
leg_opt,
"\\hspace{-.6cm}{\\textbf{$(sp[:legend_title])}}",
false,
),
)
end
for (series_index, series) in enumerate(series_list(sp))
# give each series a uuid for fillbetween
series_id = uuid4()
_pgfplotsx_series_ids[Symbol("$series_index")] = series_id
opt = series.plotattributes
st = series[:seriestype]
extra_series, extra_series_opt = pgfx_split_extra_kw(series[:extra_kwargs])
series_opt = merge(
Options(
"color" => single_color(opt[:linecolor]),
"name path" => string(series_id),
),
Options(extra_series_opt...),
)
series_func =
if (
RecipesPipeline.is3d(series) ||
st in (:heatmap, :contour) ||
(st === :quiver && opt[:z] !== nothing)
)
PGFPlotsX.Plot3
else
PGFPlotsX.Plot
end
if (
series[:fillrange] !== nothing &&
series[:ribbon] === nothing &&
!isfilledcontour(series)
)
push!(series_opt, "area legend" => nothing)
end
pgfx_add_series!(Val(st), axis, series_opt, series, series_func, opt)
if extra_series !== nothing
push!(axis.contents[end], wraptuple(extra_series)...)
end
# add series annotations
anns = series[:series_annotations]
for (xi, yi, str, fnt) in EachAnn(anns, series[:x], series[:y])
pgfx_add_annotation!(
axis,
xi,
yi,
PlotText(str, fnt),
pgfx_thickness_scaling(series),
)
end
end # for series
# add subplot annotations
for ann in sp[:annotations]
pgfx_add_annotation!(
axis,
locate_annotation(sp, ann...)...,
pgfx_thickness_scaling(sp),
)
end
push!(the_plot, axis)
if length(plt.o.the_plot.elements) > 0
plt.o.the_plot.elements[1] = the_plot
else
push!(plt.o, the_plot)
end
end # for subplots
pgfx_plot.is_created = true
pgfx_plot.was_shown = false
end
return pgfx_plot
end
## seriestype specifics
function pgfx_add_series!(axis, series_opt, series, series_func, opt)
series_opt = series_func(series_opt, Table(pgfx_series_arguments(series, opt)...))
pgfx_add_legend!(push!(axis, series_opt), series, opt)
end
function pgfx_add_series!(::Val{:path}, axis, series_opt, series, series_func, opt)
# treat segments
segments = collect(series_segments(series, series[:seriestype]; check = true))
for (k, segment) in enumerate(segments)
i, rng = segment.attr_index, segment.range
segment_opt = merge(Options(), pgfx_linestyle(opt, i))
if opt[:markershape] !== :none
if (marker = _cycle(opt[:markershape], i)) isa Shape
scale_factor = 0.00125
msize = opt[:markersize] * scale_factor
path = join(
map((x, y) -> "($(x * msize), $(y * msize))", marker.x, marker.y),
" -- ",
)
PGFPlotsX.push_preamble!(
series[:plot_object].o.the_plot,
"""
\\pgfdeclareplotmark{PlotsShape$(series[:series_plotindex])}{
\\filldraw
$path;
}
""",
)
end
segment_opt = merge(segment_opt, pgfx_marker(opt, i))
end
# add fillrange
if (sf = opt[:fillrange]) !== nothing && !isfilledcontour(series)
if sf isa Number || sf isa AVec
pgfx_fillrange_series!(axis, series, series_func, i, _cycle(sf, rng), rng)
elseif sf isa Tuple && series[:ribbon] !== nothing
for sfi in sf
pgfx_fillrange_series!(
axis,
series,
series_func,
i,
_cycle(sfi, rng),
rng,
)
end
end
if (
i == 1 &&
series[:subplot][:legend_position] !== :none &&
pgfx_should_add_to_legend(series)
)
pgfx_filllegend!(series_opt, opt)
end
end
# handle arrows
coordinates = if (arrow = opt[:arrow]) isa Arrow
arrow_opt = merge(
segment_opt,
Options(
"quiver" => Options(
"u" => "\\thisrow{u}",
"v" => "\\thisrow{v}",
pgfx_arrow(arrow, :head) => nothing,
),
),
)
isempty(opt[:label]) && push!(arrow_opt, "forget plot" => nothing)
rx, ry = opt[:x][rng], opt[:y][rng]
nx, ny = length(rx), length(ry)
x_arrow, y_arrow, x_path, y_path = if arrow.side === :head
rx[(nx - 1):nx], ry[(ny - 1):ny], rx[1:(nx - 1)], ry[1:(ny - 1)]
elseif arrow.side === :tail
rx[2:-1:1], ry[2:-1:1], rx[2:nx], ry[2:ny]
elseif arrow.side === :both
rx[[2, 1, nx - 1, nx]], ry[[2, 1, ny - 1, ny]], rx[2:(nx - 1)], ry[2:(ny - 1)]
end
coords = Table([
:x => x_arrow[1:2:(end - 1)],
:y => y_arrow[1:2:(end - 1)],
:u => [x_arrow[i] - x_arrow[i - 1] for i in 2:2:lastindex(x_arrow)],
:v => [y_arrow[i] - y_arrow[i - 1] for i in 2:2:lastindex(y_arrow)],
])
arrow_plot = series_func(merge(series_opt, arrow_opt), coords)
push!(series_opt, "forget plot" => nothing)
push!(axis, arrow_plot)
Table(x_path, y_path)
else
Table(pgfx_series_arguments(series, opt, rng)...)
end
push!(axis, series_func(merge(series_opt, segment_opt), coordinates))
# fill between functions
if sf isa Tuple && series[:ribbon] === nothing
sf1, sf2 = sf
@assert sf1 == series_index "First index of the tuple has to match the current series index."
push!(
axis,
series_func(
merge(
pgfx_fillstyle(opt, series_index),
Options("forget plot" => nothing),
),
"fill between [of=$series_id and $(_pgfplotsx_series_ids[Symbol(string(sf2))])]",
),
)
end
pgfx_add_legend!(axis, series, opt, k)
end # for segments
# get that last marker
if !isnothing(opt[:y]) && !any(isnan, opt[:y]) && opt[:markershape] isa AVec
push!(
axis,
PGFPlotsX.PlotInc( # additional plot
pgfx_marker(opt, length(segments) + 1),
PGFPlotsX.Coordinates(tuple((last(opt[:x]), last(opt[:y])))),
),
)
end
nothing
end
pgfx_add_series!(::Val{:straightline}, args...) = pgfx_add_series!(Val(:path), args...)
pgfx_add_series!(::Val{:path3d}, args...) = pgfx_add_series!(Val(:path), args...)
function pgfx_add_series!(::Val{:scatter}, axis, series_opt, args...)
push!(series_opt, "only marks" => nothing)
pgfx_add_series!(Val(:path), axis, series_opt, args...)
end
function pgfx_add_series!(::Val{:scatter3d}, axis, series_opt, args...)
push!(series_opt, "only marks" => nothing)
pgfx_add_series!(Val(:path), axis, series_opt, args...)
end
function pgfx_add_series!(::Val{:surface}, axis, series_opt, series, series_func, opt)
push!(
series_opt,
"surf" => nothing,
"mesh/rows" => length(unique(opt[:x])), # unique if its all vectors
"mesh/cols" => length(unique(opt[:y])),
"z buffer" => "sort",
"opacity" => something(get_fillalpha(series), 1.0),
)
pgfx_add_series!(axis, series_opt, series, series_func, opt)
end
function pgfx_add_series!(::Val{:wireframe}, axis, series_opt, series, series_func, opt)
push!(series_opt, "mesh" => nothing, "mesh/rows" => length(opt[:x]))
pgfx_add_series!(axis, series_opt, series, series_func, opt)
end
function pgfx_add_series!(::Val{:heatmap}, axis, series_opt, series, series_func, opt)
push!(axis.options, "view" => "{0}{90}")
push!(
series_opt,
"matrix plot*" => nothing,
"mesh/rows" => length(opt[:x]),
"mesh/cols" => length(opt[:y]),
"point meta" => "\\thisrow{meta}",
)
args = pgfx_series_arguments(series, opt)
meta = map(r -> any(!isfinite, r) ? NaN : r[3], zip(args...))
for arg in args
arg[(!isfinite).(arg)] .= 0
end
table = Table(["x" => args[1], "y" => args[2], "z" => args[3], "meta" => meta])
push!(axis, series_func(series_opt, table))
pgfx_add_legend!(axis, series, opt)
end
function pgfx_add_series!(::Val{:mesh3d}, axis, series_opt, series, series_func, opt)
ptable = if (cns = opt[:connections]) isa Tuple{Array,Array,Array} # 0-based indexing
map((i, j, k) -> "$i $j $k\\\\", cns...)
elseif typeof(cns) <: AVec{NTuple{3,Int}} # 1-based indexing
map(c -> "$(c[1] - 1) $(c[2] - 1) $(c[3] - 1)\\\\", cns)
else
"""
Argument connections has to be either a tuple of three arrays (0-based indexing)
or an AbstractVector{NTuple{3,Int}} (1-based indexing).
""" |>
ArgumentError |>
throw
end
push!(
series_opt,
"patch" => nothing,
"table/row sep" => "\\\\",
"patch table" => join(ptable, "\n "),
)
pgfx_add_series!(axis, series_opt, series, series_func, opt)
end
function pgfx_add_series!(::Val{:contour}, axis, series_opt, series, series_func, opt)
push!(axis.options, "view" => "{0}{90}")
if isfilledcontour(series)
pgfx_add_series!(Val(:filledcontour), axis, series_opt, series, series_func, opt)
return nothing
end
pgfx_add_series!(Val(:contour3d), axis, series_opt, series, series_func, opt)
end
function pgfx_add_series!(::Val{:filledcontour}, axis, series_opt, series, series_func, opt)
push!(
series_opt,
"contour filled" => Options(), # labels not supported
"patch type" => "bilinear",
"shader" => "flat",
)
if (levels = opt[:levels]) isa Number
push!(series_opt["contour filled"], "number" => levels)
elseif levels isa AVec
push!(series_opt["contour filled"], "levels" => levels)
end
pgfx_add_series!(axis, series_opt, series, series_func, opt)
end
function pgfx_add_series!(::Val{:contour3d}, axis, series_opt, series, series_func, opt)
push!(series_opt, "contour prepared" => Options("labels" => opt[:contour_labels]))
push!(
axis,
series_func(
merge(series_opt, pgfx_linestyle(opt)),
Table(Contour.contours(pgfx_series_arguments(series, opt)..., opt[:levels])),
),
)
pgfx_add_legend!(axis, series, opt)
end
function pgfx_add_series!(::Val{:quiver}, axis, series_opt, series, series_func, opt)
if (quiver = opt[:quiver]) !== nothing
push!(
series_opt,
"quiver" => Options(
"u" => "\\thisrow{u}",
"v" => "\\thisrow{v}",
pgfx_arrow(opt[:arrow]) => nothing,
),
)
x, y, z = opt[:x], opt[:y], opt[:z]
table = if z !== nothing
push!(series_opt["quiver"], "w" => "\\thisrow{w}")
pgfx_axis!(axis.options, series[:subplot], :z)
[:x => x, :y => y, :z => z, :u => quiver[1], :v => quiver[2], :w => quiver[3]]
else
[:x => x, :y => y, :u => quiver[1], :v => quiver[2]]
end
pgfx_add_legend!(push!(axis, series_func(series_opt, Table(table))), series, opt)
end
nothing
end
function pgfx_add_series!(::Val{:shape}, axis, series_opt, series, series_func, opt)
series_opt = merge(push!(series_opt, "area legend" => nothing), pgfx_fillstyle(opt))
pgfx_add_series!(Val(:path), axis, series_opt, series, series_func, opt)
end
function pgfx_add_series!(::Val{:steppre}, axis, series_opt, args...)
push!(series_opt, "const plot mark right" => nothing)
pgfx_add_series!(Val(:path), axis, series_opt, args...)
end
function pgfx_add_series!(::Val{:stepmid}, axis, series_opt, args...)
push!(series_opt, "const plot mark mid" => nothing)
pgfx_add_series!(Val(:path), axis, series_opt, args...)
end
function pgfx_add_series!(::Val{:steppost}, axis, series_opt, args...)
push!(series_opt, "const plot" => nothing)
pgfx_add_series!(Val(:path), axis, series_opt, args...)
end
function pgfx_add_series!(::Val{:ysticks}, axis, series_opt, args...)
push!(series_opt, "const plot" => nothing)
pgfx_add_series!(Val(:path), axis, series_opt, args...)
end
function pgfx_add_series!(::Val{:xsticks}, axis, series_opt, args...)
push!(series_opt, "const plot" => nothing)
pgfx_add_series!(Val(:path), axis, series_opt, args...)
end
function pgfx_add_legend!(axis, series, opt, i = 1)
if series[:subplot][:legend_position] !== :none
leg_entry = if (lab = opt[:label]) isa AVec
get(lab, i, "")
elseif lab isa AbstractString
i == 1 ? lab : ""
else
throw(ArgumentError("Malformed label `$lab`"))
end
if isempty(leg_entry) || !pgfx_should_add_to_legend(series)
push!(axis.contents[end].options, "forget plot" => nothing)
else
push!(axis, PGFPlotsX.LegendEntry(Options(), leg_entry, false))
end
end
nothing
end
pgfx_series_arguments(series, opt, range) =
map(a -> a[range], pgfx_series_arguments(series, opt))
pgfx_series_arguments(series, opt) =
if (st = series[:seriestype]) in (:contour, :contour3d)
opt[:x], opt[:y], handle_surface(opt[:z])
elseif st in (:heatmap, :surface, :wireframe)
surface_to_vecs(opt[:x], opt[:y], opt[:z])
elseif RecipesPipeline.is3d(st)
opt[:x], opt[:y], opt[:z]
elseif st === :straightline
straightline_data(series)
elseif st === :shape
shape_data(series)
elseif ispolar(series)
theta, r = opt[:x], opt[:y]
rad2deg.(theta), r
else
opt[:x], opt[:y]
end
pgfx_get_linestyle(k::AbstractString) = pgfx_get_linestyle(Symbol(k))
pgfx_get_linestyle(k::Symbol) = get(
(
solid = "solid",
dash = "dashed",
dot = "dotted",
dashdot = "dashdotted",
dashdotdot = "dashdotdotted",
),
k,
"solid",
)
pgfx_get_marker(k::AbstractString) = pgfx_get_marker(Symbol(k))
pgfx_get_marker(k::Symbol) = get(
(
none = "none",
cross = "+",
xcross = "x",
(+) = "+",
x = "x",
utriangle = "triangle*",
dtriangle = "triangle*",
rtriangle = "triangle*",
ltriangle = "triangle*",
circle = "*",
rect = "square*",
star5 = "star",
star6 = "asterisk",
diamond = "diamond*",
pentagon = "pentagon*",
hline = "-",
vline = "|",
),
k,
"*",
)
pgfx_get_xguide_pos(k::AbstractString) = pgfx_get_xguide_pos(Symbol(k))
pgfx_get_xguide_pos(k::Symbol) = get(
(
top = "at={(0.5,1)},above,",
right = "at={(ticklabel* cs:1.02)}, anchor=west,",
left = "at={(ticklabel* cs:-0.02)}, anchor=east,",
),
k,
"at={(ticklabel cs:0.5)}, anchor=near ticklabel",
)
pgfx_get_yguide_pos(k::AbstractString) = pgfx_get_yguide_pos(Symbol(k))
pgfx_get_yguide_pos(k::Symbol) = get(
(
top = "at={(ticklabel* cs:1.02)}, anchor=south",
right = "at={(1,0.5)},below,",
bottom = "at={(ticklabel* cs:-0.02)}, anchor=north,",
),
k,
"at={(ticklabel cs:0.5)}, anchor=near ticklabel",
)
pgfx_get_legend_pos(k::AbstractString) = pgfx_get_legend_pos(Symbol(k))
pgfx_get_legend_pos(t::Tuple{<:Real,<:Real}) = ("at" => curly(t), "anchor" => "north west")
pgfx_get_legend_pos(nt::NamedTuple) = ("at" => curly(nt.at), "anchor" => string(nt.anchor))
pgfx_get_legend_pos(theta::Real) = pgfx_get_legend_pos((theta, :inner))
pgfx_get_legend_pos(k::Symbol) = get(
(
top = ("at" => "(0.5, 0.98)", "anchor" => "north"),
bottom = ("at" => "(0.5, 0.02)", "anchor" => "south"),
left = ("at" => "(0.02, 0.5)", "anchor" => "west"),
right = ("at" => "(0.98, 0.5)", "anchor" => "east"),
bottomleft = ("at" => "(0.02, 0.02)", "anchor" => "south west"),
bottomright = ("at" => "(0.98, 0.02)", "anchor" => "south east"),
topright = ("at" => "(0.98, 0.98)", "anchor" => "north east"),
topleft = ("at" => "(0.02, 0.98)", "anchor" => "north west"),
outertop = ("at" => "(0.5, 1.02)", "anchor" => "south"),
outerbottom = ("at" => "(0.5, -0.02)", "anchor" => "north"),
outerleft = ("at" => "(-0.02, 0.5)", "anchor" => "east"),
outerright = ("at" => "(1.02, 0.5)", "anchor" => "west"),
outerbottomleft = ("at" => "(-0.02, -0.02)", "anchor" => "north east"),
outerbottomright = ("at" => "(1.02, -0.02)", "anchor" => "north west"),
outertopright = ("at" => "(1.02, 1)", "anchor" => "north west"),
outertopleft = ("at" => "(-0.02, 1)", "anchor" => "north east"),
),
k,
("at" => "(1.02, 1)", "anchor" => "north west"),
)
function pgfx_get_legend_pos(v::Tuple{<:Real,Symbol})
s, c = sincosd(first(v))
anchors = [
"south west" "south" "south east"
"west" "center" "east"
"north west" "north" "north east"
]
I = legend_anchor_index(s)
rect, anchor = if v[2] === :inner
(0.07, 0.5, 1.0, 0.07, 0.52, 1.0), anchors[I, I]
else
(-0.15, 0.5, 1.05, -0.15, 0.52, 1.1), anchors[4 - I, 4 - I]
end
return "at" => string(legend_pos_from_angle(v[1], rect...)), "anchor" => anchor
end
function pgfx_get_legend_style(sp)
cstr = plot_color(sp[:legend_background_color])
Options(
pgfx_linestyle(
pgfx_thickness_scaling(sp),
sp[:legend_foreground_color],
alpha(plot_color(sp[:legend_foreground_color])),
"solid",
) => nothing,
"fill" => cstr,
"fill opacity" => alpha(cstr),
"text opacity" => alpha(plot_color(sp[:legend_font_color])),
"font" => pgfx_font(sp[:legend_font_pointsize], pgfx_thickness_scaling(sp)),
"text" => plot_color(sp[:legend_font_color]),
"cells" => Options(
"anchor" => get(
(left = "west", right = "east", hcenter = "center"),
legendfont(sp).halign,
"west",
),
),
pgfx_get_legend_pos(sp[:legend_position])...,
)
end
pgfx_get_colorbar_pos(k::AbstractString) = pgfx_get_colorbar_pos(Symbol(k))
pgfx_get_colorbar_pos(b::Bool) = ""
pgfx_get_colorbar_pos(s::Symbol) =
get((left = " left", bottom = " horizontal", top = " horizontal"), s, "")
pgfx_get_title_pos(k::AbstractString) = pgfx_get_title_pos(Symbol(k))
pgfx_get_title_pos(t::Tuple) = ("at" => curly(t), "anchor" => "south")
pgfx_get_title_pos(nt::NamedTuple) = ("at" => curly(nt.at), "anchor" => string(nt.anchor))
pgfx_get_title_pos(s::Symbol) = get(
(
left = ("at" => "{(0,1)}", "anchor" => "south west"),
right = ("at" => "{(1,1)}", "anchor" => "south east"),
),
s,
("at" => "{(0.5,1)}", "anchor" => "south"),
)
function pgfx_get_ticklabel_style(sp, axis)
cstr = plot_color(axis[:tickfontcolor])
return Options(
"font" => pgfx_font(axis[:tickfontsize], pgfx_thickness_scaling(sp)),
"color" => cstr,
"draw opacity" => alpha(cstr),
"rotate" => axis[:tickfontrotation],
)
end
function pgfx_get_colorbar_ticklabel_style(sp)
cstr = plot_color(sp[:colorbar_tickfontcolor])
return Options(
"font" => pgfx_font(sp[:colorbar_tickfontsize], pgfx_thickness_scaling(sp)),
"color" => cstr,
"draw opacity" => alpha(cstr),
"rotate" => sp[:colorbar_tickfontrotation],
)
end
function pgfx_get_colorbar_title_style(sp)
cstr = plot_color(sp[:colorbar_titlefontcolor])
return Options(
"font" => pgfx_font(sp[:colorbar_titlefontsize], pgfx_thickness_scaling(sp)),
"color" => cstr,
"draw opacity" => alpha(cstr),
"rotate" => sp[:colorbar_titlefontrotation],
)
end
## --------------------------------------------------------------------------------------
pgfx_arrow(::Nothing) = "every arrow/.append style={-}"
function pgfx_arrow(arr::Arrow, side = arr.side)
components = ""
arrow_head = "{stealth[length = $(arr.headlength)pt, width = $(arr.headwidth)pt"
arr.style === :open && (arrow_head *= ", open")
arrow_head *= "]}"
(side === :both || side === :tail) && (components *= arrow_head)
components *= "-"
(side === :both || side === :head) && (components *= arrow_head)
return "every arrow/.append style={$components}"
end
function pgfx_filllegend!(series_opt, opt)
style = strip(sprint(PGFPlotsX.print_tex, pgfx_fillstyle(opt)), ['[', ']', ' '])
push!(
series_opt,
"legend image code/.code" => "{\n\\draw[$style] (0cm,-0.1cm) rectangle (0.6cm,0.1cm);\n}",
)
end
# Generates a colormap for pgfplots based on a ColorGradient
pgfx_colormap(cl::PlotUtils.AbstractColorList) = pgfx_colormap(color_list(cl))
pgfx_colormap(v::Vector{<:Colorant}) =
join(map(c -> @sprintf("rgb=(%.8f,%.8f,%.8f)", red(c), green(c), blue(c)), v), '\n')
pgfx_colormap(cg::ColorGradient) = join(
map(1:length(cg)) do i
@sprintf(
"rgb(%.8f)=(%.8f,%.8f,%.8f)",
cg.values[i],
red(cg.colors[i]),
green(cg.colors[i]),
blue(cg.colors[i])
)
end,
'\n',
)
pgfx_framestyle(style::Symbol) =
if style in (:box, :axes, :origin, :zerolines, :grid, :none)
style
else
default_style = style === :semi ? :box : :axes
@warn "Framestyle :$style is not (yet) supported by the PGFPlotsX backend. :$default_style was chosen instead."
default_style
end
pgfx_thickness_scaling(plt::Plot) = plt[:thickness_scaling]
pgfx_thickness_scaling(sp::Subplot) = pgfx_thickness_scaling(sp.plt)
pgfx_thickness_scaling(series) = pgfx_thickness_scaling(series[:subplot])
function pgfx_fillstyle(plotattributes, i = 1)
if (a = get_fillalpha(plotattributes, i)) === nothing
a = alpha(single_color(get_fillcolor(plotattributes, i)))
end
Options("fill" => get_fillcolor(plotattributes, i), "fill opacity" => a)
end
function pgfx_linestyle(linewidth::Real, color, α = 1, linestyle = :solid)
cstr = plot_color(color, α)
return Options(
"color" => cstr,
"draw opacity" => alpha(cstr),
"line width" => linewidth,
pgfx_get_linestyle(linestyle) => nothing,
)
end
pgfx_legend_col(s::Symbol) = s === :horizontal ? -1 : 1
pgfx_legend_col(n) = n
function pgfx_linestyle(plotattributes, i = 1)
lw = pgfx_thickness_scaling(plotattributes) * get_linewidth(plotattributes, i)
lc = single_color(get_linecolor(plotattributes, i))
la = get_linealpha(plotattributes, i)
ls = get_linestyle(plotattributes, i)
return pgfx_linestyle(lw, lc, la, ls)
end
function pgfx_font(fontsize, thickness_scaling = 1, font = "\\selectfont")
fs = fontsize * thickness_scaling
return "{\\fontsize{$fs pt}{$(1.3fs) pt}$font}"
end
# If a particular fontsize parameter is `nothing`, produce a figure that doesn't specify the
# font size, and therefore uses whatever fontsize is utilised by the doc in which the
# figure is located.
pgfx_font(fontsize::Nothing, thickness_scaling = 1, font = "\\selectfont") = curly(font)
pgfx_should_add_to_legend(series::Series) =
series.plotattributes[:primary] &&
series.plotattributes[:seriestype] ∉ (
:hexbin,
:bins2d,
:histogram2d,
:hline,
:vline,
:contour,
:contourf,
:contour3d,
:heatmap,
:image,
)
function pgfx_marker(plotattributes, i = 1)
shape = _cycle(plotattributes[:markershape], i)
cstr =
plot_color(get_markercolor(plotattributes, i), get_markeralpha(plotattributes, i))
cstr_stroke = plot_color(
get_markerstrokecolor(plotattributes, i),
get_markerstrokealpha(plotattributes, i),
)
mark_size =
pgfx_thickness_scaling(plotattributes) *
0.75 *
_cycle(plotattributes[:markersize], i)
mark_freq = if !any(isnan, plotattributes[:y]) && plotattributes[:markershape] isa AVec
length(plotattributes[:markershape])
else
1
end
return Options(
"mark" => shape isa Shape ? "PlotsShape$i" : pgfx_get_marker(shape),
"mark size" => "$mark_size pt",
"mark repeat" => mark_freq,
"mark options" => Options(
"color" => cstr_stroke,
"draw opacity" => alpha(cstr_stroke),
"fill" => cstr,
"fill opacity" => alpha(cstr),
"line width" =>
pgfx_thickness_scaling(plotattributes) *
0.75 *
_cycle(plotattributes[:markerstrokewidth], i),
"rotate" => if shape === :dtriangle
180
elseif shape === :rtriangle
270
elseif shape === :ltriangle
90
else
0
end,
pgfx_get_linestyle(_cycle(plotattributes[:markerstrokestyle], i)) =>
nothing,
),
)
end
function pgfx_add_annotation!(
o,
x,
y,
val,
thickness_scaling = 1;
cs = "axis cs:",
options = Options(),
)
# Construct the style string.
cstr = val.font.color
ann_opt = merge(
Options(
get((hcenter = "", left = "right", right = "left"), val.font.halign, "") =>
nothing,
"color" => cstr,
"draw opacity" => float(alpha(cstr)), # float(...): convert N0f8
"rotate" => val.font.rotation,
"font" => pgfx_font(val.font.pointsize, thickness_scaling),
),
options,
)
push!(o, "\\node$(sprint(PGFPlotsX.print_tex, ann_opt)) at ($(cs)$x,$y) {$(val.str)};")
end
function pgfx_fillrange_series!(axis, series, series_func, i, fillrange, rng)
fr_opt = Options("line width" => "0", "draw opacity" => "0")
fr_opt = merge(fr_opt, pgfx_fillstyle(series, i))
push!(