/
PGFPlots.jl
938 lines (834 loc) · 29.4 KB
/
PGFPlots.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
module PGFPlots
export LaTeXString, @L_str, @L_mstr
export plot, tikzCode, ErrorBars, Axis, Axes, PolarAxis, SmithAxis, TernaryAxis, GroupPlot, Plots, ColorMaps, save, define_color
export pushPGFPlotsOptions, popPGFPlotsOptions, resetPGFPlotsOptions, pgfplotsoptions
export pushPGFPlotsPreamble, popPGFPlotsPreamble, resetPGFPlotsPreamble, pgfplotspreamble
export pushPGFPlots, popPGFPlots
import Colors: RGB
import Contour: contours, levels
using Requires
using Discretizers
using Printf
# Define isnothing
if VERSION < v"1.1"
isnothing(x) = x === nothing
end
# load dynamic dependencies
function __init__()
@require DataFrames="a93c6f00-e57d-5684-b7b6-d8193f3e46c0" include("dataframes.jl")
end
mutable struct ErrorBars
data::AbstractMatrix{Real}
style
mark
ErrorBars(data::AbstractMatrix{T}; style=nothing, mark=nothing) where {T <: Real} = new(data, style, mark)
end
mylength(x) = isnothing(x) ? 0 : length(x)
function ErrorBars(; x=nothing, y=nothing, xplus=nothing, xminus=nothing, yplus=nothing, yminus=nothing, style=nothing, mark=nothing)
if x != nothing
xplus = x
xminus = x
end
if y != nothing
yplus = y
yminus = y
end
n = maximum(map(mylength, Any[xplus, xminus, yplus, yminus]))
xplus = mylength(xplus) == n ? xplus : zeros(n)
xminus = mylength(xminus) == n ? xminus : zeros(n)
yplus = mylength(yplus) == n ? yplus : zeros(n)
yminus = mylength(yminus) == n ? yminus : zeros(n)
data = hcat(xplus, xminus, yplus, yminus)'
ErrorBars(data, style=style, mark=mark)
end
include("colormaps.jl")
include("plots.jl")
import TikzPictures: TikzPicture, PDF, TEX, TIKZ, SVG, save, LaTeXString, @L_str, @L_mstr
_pgfplotsoptions = Any[""]
pushPGFPlotsOptions(options::AbstractString) = push!(_pgfplotsoptions, options)
function popPGFPlotsOptions()
if length(_pgfplotsoptions) > 1
pop!(_pgfplotsoptions)
end
end
resetPGFPlotsOptions() = deleteat!(_pgfplotsoptions, 2:length(_pgfplotsoptions))
function pushPGFPlots(options::AbstractString)
warn("Use pushPGFPlotsOptions")
pushPGFPlotsOptions(options)
end
function popPGFPlots()
warn("Use popPGFPlotsOptions")
popPGFPlotsOptions()
end
pgfplotsoptions() = join(_pgfplotsoptions, ",\n")
_pgfplotspreamble = Any[read(joinpath(dirname(@__FILE__), "preamble.tex"),String)]
pushPGFPlotsPreamble(preamble::AbstractString) = push!(_pgfplotspreamble, preamble)
function popPGFPlotsPreamble()
if length(_pgfplotspreamble) > 1
pop!(_pgfplotspreamble)
end
end
resetPGFPlotsPreamble() = deleteat!(_pgfplotspreamble,2:length(_pgfplotspreamble))
pgfplotspreamble() = join(_pgfplotspreamble, "\n")
function define_color(name::AbstractString, color::RGB)
_pgfplotspreamble[end] = _pgfplotspreamble[end] * "\n\\definecolor{$name}{rgb}{$(color.r), $(color.g), $(color.b)}"
end
define_color(name::AbstractString, color) = define_color(name, convert(RGB, color))
function define_color(name::AbstractString, color::Vector{T}) where {T<:AbstractFloat}
if length(color) == 3
r, g, b = color[1], color[2], color[3]
_pgfplotspreamble[end] = _pgfplotspreamble[end] * "\n\\definecolor{$name}{rgb}{$r, $g, $b}"
elseif length(color) == 4
c, m, y, k = color[1], color[2], color[3], color[4]
_pgfplotspreamble[end] = _pgfplotspreamble[end] * "\n\\definecolor{$name}{cmyk}{$c, $m, $y, $k}"
else
error("Color must have three or four components")
end
end
function define_color(name::AbstractString, color::Vector{T}) where {T<:Integer}
@assert(length(color) == 3, "Color must have three components")
r, g, b = color[1], color[2], color[3]
_pgfplotspreamble[end] = _pgfplotspreamble[end] * "\n\\definecolor{$name}{RGB}{$r, $g, $b}"
end
function define_color(name::AbstractString, color::UInt32)
_pgfplotspreamble[end] = _pgfplotspreamble[end] * "\n\\definecolor{$name}{HTML}{$(uppercase(string(color, base=16)))}"
end
function define_color(name::AbstractString, color::Real)
_pgfplotspreamble[end] = _pgfplotspreamble[end] * "\n\\definecolor{$name}{gray}{$color}"
end
histogramMap = Dict(
:bins => "bins",
:density => "density",
:cumulative => "cumulative"
)
linearMap = Dict(
:mark => "mark",
:markSize => "mark size",
:style => "",
:onlyMarks => "only marks"
)
barMap = Dict(
:style => ""
)
scatterMap = Dict(
:mark => "mark",
:markSize => "mark size",
:style => "",
:onlyMarks => "only marks",
:scatterClasses => "scatter/classes"
)
errorbarsMap = Dict(
:mark => "error mark",
:style => "error bar style"
)
quiverMap = Dict(
:style => ""
)
contourMap = Dict(
:number => "number",
:levels => "levels",
:style => "",
:labels => "labels"
)
patch2DMap = Dict(
:style => "",
:patch_type => "patch type",
:shader => "shader",
:legendentry => "legendentry"
)
using .Plots
using .ColorMaps
const IntegerRange = Tuple{Integer,Integer}
const RealRange = Tuple{Real,Real}
mutable struct Axis
plots::Vector{Plot}
title
xlabel
xlabelStyle
ylabel
ylabelStyle
zlabel
zlabelStyle
xmin
xmax
ymin
ymax
axisEqual
axisEqualImage
enlargelimits
axisOnTop
view
width
height
style
legendPos
legendStyle
xmode
ymode
colorbar
colorbarStyle
hideAxis
axisLines
axisKeyword
Axis(plots::Vector{P};title=nothing, xlabel=nothing, xlabelStyle=nothing, ylabel=nothing, ylabelStyle=nothing, zlabel=nothing, zlabelStyle=nothing, xmin=nothing, xmax=nothing,
ymin=nothing, ymax=nothing, axisEqual=nothing, axisEqualImage=nothing, enlargelimits=nothing, axisOnTop=nothing, view=nothing, width=nothing,
height=nothing, style=nothing, legendPos=nothing, legendStyle=nothing, xmode=nothing, ymode=nothing, colorbar=nothing, colorbarStyle=nothing, hideAxis=nothing, axisLines=nothing, axisKeyword="axis") where {P <: Plot} =
new(plots, title, xlabel, xlabelStyle, ylabel, ylabelStyle, zlabel, zlabelStyle, xmin, xmax, ymin, ymax, axisEqual, axisEqualImage, enlargelimits, axisOnTop, view, width, height, style, legendPos, legendStyle, xmode, ymode, colorbar, colorbarStyle, hideAxis, axisLines, axisKeyword
)
Axis(;kwargs...) = Axis(Plot[]; kwargs...)
Axis(plot::Plot; kwargs...) = Axis(Plot[plot]; kwargs...)
Axis(plot::Contour; kwargs...) = Axis(Plot[plot]; kwargs..., view="{0}{90}")
Axis(plots::Vector{Contour}; kwargs...) = Axis(Plot[plots...]; kwargs..., view="{0}{90}")
end
function PolarAxis(args...; kwargs...)
ternary_axis_string = "\\usepgfplotslibrary{polar}"
if ternary_axis_string ∉ _pgfplotspreamble
pushPGFPlotsPreamble(ternary_axis_string)
end
return Axis(args...; kwargs..., axisKeyword = "polaraxis")
end
function TernaryAxis(args...; kwargs...)
ternary_axis_string = "\\usepgfplotslibrary{ternary}"
if ternary_axis_string ∉ _pgfplotspreamble
pushPGFPlotsPreamble(ternary_axis_string)
end
return Axis(args...; kwargs..., axisKeyword = "ternaryaxis")
end
function SmithAxis(args...; kwargs...)
ternary_axis_string = "\\usepgfplotslibrary{smithchart}"
if ternary_axis_string ∉ _pgfplotspreamble
pushPGFPlotsPreamble(ternary_axis_string)
end
return Axis(args...; kwargs..., axisKeyword = "smithchart")
end
const Axes = Vector{Axis}
function Base.push!(g::Axis, p::Plot)
push!(g.plots, p)
end
axisMap = Dict(
:title => "title",
:xlabel => "xlabel",
:xlabelStyle => "xlabel style",
:ylabel => "ylabel",
:ylabelStyle => "ylabel style",
:zlabel => "zlabel",
:zlabelStyle => "zlabel style",
:xmin => "xmin",
:xmax => "xmax",
:ymin => "ymin",
:ymax => "ymax",
:axisEqual => "axis equal",
:axisEqualImage => "axis equal image",
:enlargelimits => "enlargelimits",
:axisOnTop => "axis on top",
:view => "view",
:width => "width",
:height => "height",
:style => "",
:legendPos => "legend pos",
:legendStyle => "legend style",
:xmode => "xmode",
:ymode => "ymode",
:colorbar => "colorbar",
:colorbarStyle => "colorbar style",
:hideAxis => "hide axis",
:axisLines => "axis lines"
)
mutable struct GroupPlot
axes::AbstractArray{Axis,1}
dimensions::IntegerRange
style
groupStyle
GroupPlot(;style=nothing,groupStyle=nothing) = new(AbstractArray{Axis,1}[], (0,0), style, groupStyle)
GroupPlot(axes::AbstractArray{Axis,1};style=nothing,groupStyle=nothing) = new(axes, (length(axes), 1), style, groupStyle)
GroupPlot(plots;style=nothing,groupStyle=nothing) = new([Axis(p) for p in plots], (length(plots), 1), style, groupStyle)
GroupPlot(dimensions::IntegerRange;style=nothing,groupStyle=nothing) = new(AbstractArray{Axis,1}[], dimensions, style, groupStyle)
GroupPlot(rows::Integer, columns::Integer;style=nothing,groupStyle=nothing) = new(AbstractArray{Axis,1}[], (rows, columns), style, groupStyle)
end
function Base.push!(g::GroupPlot, a::Axis)
push!(g.axes, a)
if length(g.axes) > prod(g.dimensions)
g.dimensions = (length(g.axes), 1)
end
g
end
Base.push!(g::GroupPlot, p::Plot) = push!(g, Axis(p))
function Base.append!(g::GroupPlot, arr::AbstractVector{T}) where {T<:Union{Plot,Axis}}
for a in arr
push!(g, a)
end
g
end
function printList(o::IO, a::AbstractVector; brackets=false)
first = true
for elem in a
if first
first = false
if brackets
print(o, "{")
end
print(o, "$elem")
else
print(o, ", $elem")
end
end
if !first && brackets
print(o, "}")
end
end
function nextOptionHelper(o::IO, isFirst::Bool, brackets::Bool, breakLine::Bool=true)
if isFirst && brackets
print(o, "[\n ")
elseif !isFirst && breakLine
print(o, ",\n ")
elseif !isFirst
print(o, ", ")
end
return false # used to set isFirst=false
end
function optionHelper(o::IO, m, object; brackets::Bool=true, preOptions::Vector{T}=String[], postOptions::Vector{T}=String[], wrapIn::String="") where T <: AbstractString
isFirst = true
for t in preOptions
isFirst = nextOptionHelper(o, isFirst, brackets)
print(o, t)
end
if length(wrapIn) > 0
nextOptionHelper(o, isFirst, brackets)
print(o, "$wrapIn = {")
isFirst = true # temporarily true inside brackets
end
for (sym, str) in m
if !isnothing(getfield(object, sym)) && getfield(object, sym) != ""
isFirst = nextOptionHelper(o, isFirst, length(wrapIn)==0 && brackets, length(wrapIn)==0)
if length(str) > 0
print(o, "$str = {$(getfield(object, sym))}") # wrap with keyword
else
print(o, string(getfield(object, sym))) # print directly, without keyword
end
end
end
if length(wrapIn) > 0
print(o, "}")
isFirst = false
end
for t in postOptions
isFirst = nextOptionHelper(o, isFirst, brackets)
print(o, t)
end
if !isFirst && brackets
print(o, "\n]")
end
end
function plotHelper(o::IO, p::Plots.Histogram)
if (p.discretization == :pgfplots && p.bins > 0) ||
(p.discretization == :default && length(p.data) ≤ Plots.THRESHOLD_NSAMPLES_DISC_OURSELVES)
print(o, "\\addplot+")
optionHelper(o, histogramMap, p; preOptions=["mark = none", p.style], wrapIn="hist")
println(o, " table[\n row sep=\\\\,\n y index = 0\n] { data \\\\")
for d in p.data
println(o, " $d \\\\ ")
end
println(o, "};")
else
# discretize using Discretizers.jl
if p.discretization == :specified && p.bins > 0
edges = binedges(DiscretizeUniformWidth(p.bins), convert(Vector{Float64}, p.data))
else
discretization = p.discretization == :default ? :auto : p.discretization
edges = binedges(DiscretizeUniformWidth(discretization), convert(Vector{Float64}, p.data))
end
linear = Plots._construct_histogram_linear_data(p.data, edges, p.density, p.cumulative)
if p.style != "fill=blue!10"
linear.style = p.style
if !occursin("ybar interval", linear.style)
linear.style = "ybar interval," * linear.style
end
end
plotHelper(o, linear)
end
end
function plotHelper(o::IO, p::BarChart)
print(o, "\\addplot+")
if isnothing(p.errorBars)
optionHelper(o, barMap, p)
println(o, " coordinates {")
for (k,v) in zip(p.keys, p.values)
println(o, " ($k, $v)")
end
println(o, "};")
else
plotHelperErrorBars(o, p)
end
end
function PGFPlots.Axis(p::BarChart; kwargs...)
# TODO : What's a better way to do this?
style = "ybar = 0pt,\n bar width = 18pt,\n xtick = data,\n symbolic x coords = {$(Plots.symbolic_x_coords(p))}"
kwargs_unsplat = isempty(kwargs) ? Array{Pair{Symbol,Any}}(undef,0) : convert(Array{Pair{Symbol,Any}},collect(kwargs))
i = findfirst(tup->tup[1] == :style, kwargs_unsplat)
if !isnothing(i)
kwargs_unsplat[i] = :style=>(style * ", " * kwargs_unsplat[i][2])
else
push!(kwargs_unsplat, :style=>style)
end
i = findfirst(tup->tup[1] == :ymin, kwargs_unsplat)
if isnothing(i)
push!(kwargs_unsplat, :ymin=>0)
end
return Axis(Plots.Plot[p]; kwargs_unsplat...)
end
# PGFPlots allows one to define legends in (at least) three ways.
# 1. With one \legend{} command at the end, listing each legend entry
# 2. With one legend entries field in the axis header, listing each legend entry,
# 3. With individual \addlegendentry commands after each plot.
# We use (3) because sometimes we want to skip a legend entry with "forget plot".
# We have found that "forget plot" does not play nicely with (1).
# NOTE: We guard each entry with "{}{entry}". This is to ensure that entries with
# commas are properly parsed. Otherwise, an entry like $beta(1,2)$ will fail to compile.
plotLegend(o::IO, entry) = nothing
plotLegend(o::IO, entry::AbstractString) = println(o, "\\addlegendentry{{}{$entry}}")
function plotLegend(o::IO, entries::Vector{T}) where {T <: AbstractString}
for entry in entries
plotLegend(o, entry)
end
end
# todo: add error bars style
function plotHelperErrorBars(o::IO, p::Linear)
print(o, "[\n ")
optionHelper(o, linearMap, p; brackets=false)
print(o, ",\n error bars/.cd,\n ")
optionHelper(o, errorbarsMap, p.errorBars; brackets=false, postOptions=["x dir=both", "x explicit", "y dir=both", "y explicit"])
println(o, "\n] table[")
println(o, " x error plus=ex+,\n x error minus=ex-,\n y error plus=ey+,\n y error minus=ey-")
println(o, "] {")
println(o, " x y ex+ ex- ey+ ey-")
x = vcat(p.data, p.errorBars.data)
for i = 1:size(p.data, 2)
println(o, " $(x[1,i]) $(x[2,i]) $(x[3,i]) $(x[4,i]) $(x[5,i]) $(x[6,i])")
end
if p.closedCycle
println(o, "} \\closedcycle;")
else
println(o, "};")
end
end
# todo there is a lot of code redundancy
function plotHelperErrorBars(o::IO, p::BarChart)
print(o, "[\n ")
optionHelper(o, barMap, p; brackets=false)
print(o, ",\n error bars/.cd,\n ")
optionHelper(o, errorbarsMap, p.errorBars; brackets=false, postOptions=["x dir=both", "x explicit", "y dir=both", "y explicit"])
println(o, "\n] table[")
println(o, " x error plus=ex+,\n x error minus=ex-,\n y error plus=ey+,\n y error minus=ey-")
println(o, "] {")
println(o, " x y ex+ ex- ey+ ey-")
x = p.errorBars.data
for i = 1:length(p.values)
println(o, " $(p.keys[i]) $(p.values[i]) $(x[1,i]) $(x[2,i]) $(x[3,i]) $(x[4,i])")
end
println(o, "};")
end
function plotHelper(o::IO, p::Linear)
print(o, "\\addplot+")
if isnothing(p.errorBars)
optionHelper(o, linearMap, p)
println(o, " coordinates {")
for i in 1:size(p.data,2)
println(o, " ($(p.data[1,i]), $(p.data[2,i]))")
end
if p.closedCycle
println(o, "} \\closedcycle;")
else
println(o, "};")
end
else
plotHelperErrorBars(o, p)
end
plotLegend(o, p.legendentry)
end
function plotHelper(o::IO, p::SmithData)
print(o, "\\addplot+")
optionHelper(o, linearMap, p)
println(o, " coordinates {")
for item in p.data
println(o, " ($(real(item)), $(imag(item)))")
end
println(o, "};")
plotLegend(o, p.legendentry)
end
function plotHelper(o::IO, p::SmithCircle)
if !isnothing(p.style)
println(o, "\\draw[$(p.style)] ($(p.xc), $(p.yc)) circle [radius=$(p.radius)cm];")
else
println(o, "\\draw ($(p.xc), $(p.yc)) circle [radius=$(p.radius)cm];")
end
end
function plotHelper(o::IO, p::Scatter)
print(o, "\\addplot+")
options = ["scatter", "scatter src = explicit symbolic"]
if size(p.data,1) == 2
options = ["draw = none"]
p.onlyMarks = nothing
elseif isnothing(p.scatterClasses)
options = ["scatter", "scatter src = explicit"]
end
optionHelper(o, scatterMap, p; preOptions=options)
println(o, " coordinates {")
if size(p.data,1) == 2
for i in 1:size(p.data,2)
println(o, " ($(p.data[1,i]), $(p.data[2,i]))")
end
else
for i in 1:size(p.data,2)
println(o, " ($(p.data[1,i]), $(p.data[2,i])) [$(p.data[3,i])]")
end
end
println(o, "};")
plotLegend(o, p.legendentry)
end
# Specific version for Linear3 mutable struct
# Changes are addplot3 (vs addplot) and iterate over all 3 columns
function plotHelper(o::IO, p::Linear3)
print(o, "\\addplot3+")
optionHelper(o, linearMap, p)
println(o, " coordinates {")
for i = 1:size(p.data,2)
println(o, " ($(p.data[1,i]), $(p.data[2,i]), $(p.data[3,i]))")
end
println(o, "};")
plotLegend(o, p.legendentry)
end
function plotHelper(o::IO, p::Node)
axis = !isnothing(p.axis) ? p.axis : "axis cs"
if !isnothing(p.style)
println(o, "\\node at ($(axis):$(p.x), $(p.y)) [$(p.style)] {$(p.data)};")
else
println(o, "\\node at ($(axis):$(p.x), $(p.y)) {$(p.data)};")
end
end
function plotHelper(o::IO, p::ErrorBars)
print(o, "\\addplot+")
optionHelper(o, errorbarsMap, p; postOptions=["error bars/.cd", " x dir = both", " x explicit", " y dir = both", " y explicit"])
println(o," coordinates {")
for i = 1:size(p.data,2)
println(o, " ($(p.data[1,i]), $(p.data[2,i])) +=($(p.data[3,i]),$(p.data[4,i])) -=($(p.data[5,i]),$(p.data[6,i]))")
end
println(o, "};")
plotLegend(o, p.legendentry)
end
function plotHelper(o::IO, p::Quiver)
print(o, "\\addplot+")
optionHelper(o, quiverMap, p; postOptions=["quiver = {u=\\thisrow{u}, v=\\thisrow{v}}"])
println(o, " table {")
println(o, " x y u v")
for i = 1:size(p.data,2)
println(o, " $(p.data[1,i]) $(p.data[2,i]) $(p.data[3,i]) $(p.data[4,i])")
end
println(o, "};")
plotLegend(o, p.legendentry)
end
function plotHelper(o::IO, p::Contour)
arg = 5
if !isnothing(p.number)
arg = p.number
elseif !isnothing(p.levels)
arg = p.levels
end
C = contours(convert(Vector{Float64}, p.xbins), convert(Vector{Float64}, p.ybins), convert(Matrix{Float64}, p.data), arg)
print(o, "\\addplot3[\n contour prepared")
if !isnothing(p.contour_style)
print(o, "={$(p.contour_style)}")
elseif p.labels == false
print(o, "={labels=false}")
end
if !isnothing(p.style)
print(o, ",\n $(p.style)")
end
println(o, "\n] table {")
for c in levels(C)
level = c.level
for l in c.lines
for v in l.vertices
println(o, " $(v[1]) $(v[2]) $level")
end
println(o)
end
end
println(o, "};")
end
function plotHelper(o::IO, p::Circle)
if !isnothing(p.style)
println(o, "\\draw[$(p.style)] (axis cs:$(p.xc), $(p.yc)) circle[radius=$(p.radius)];")
else
println(o, "\\draw (axis cs:$(p.xc), $(p.yc)) circle[radius=$(p.radius)];")
end
end
function plotHelper(o::IO, p::Ellipse)
if !isnothing(p.style)
println(o, "\\draw[$(p.style)] (axis cs:$(p.xc), $(p.yc)) ellipse[x radius=$(p.xradius), y radius=$(p.yradius)];")
else
println(o, "\\draw (axis cs:$(p.xc), $(p.yc)) ellipse[x radius=$(p.xradius), y radius=$(p.yradius)];")
end
end
plotHelper(o::IO, p::Command) = println(o, p.cmd * ";")
function plotHelper(o::IO, p::Image)
if p.zmin == p.zmax
error("Your colorbar range limits must not be equal to each other.")
end
print(o, "\\addplot[\n ")
if !isnothing(p.style)
println(o, join([p.style, "point meta min = $(p.zmin)", "point meta max = $(p.zmax)"], ",\n "))
else
println(o, join(["point meta min = $(p.zmin)", "point meta max = $(p.zmax)"], ",\n "))
end
print(o, "] graphics[\n ")
println(o, join(["xmin = $(p.xmin)", "xmax = $(p.xmax)", "ymin = $(p.ymin)", "ymax = $(p.ymax)"], ",\n "))
println(o, "] {$(p.filename)};")
end
function plotHelper(o::IO, p::Patch2D)
print(o, "\\addplot")
optionHelper(o, patch2DMap, p)
m = p.patch_type == "rectangle" ? 4 : 3
if size(p.data, 1) == 3 # include color
println(o, " table[\n point meta = \\thisrow{c}\n] {")
println(o, " x y c")
elseif size(p.data, 1) == 2
println(o, " table {")
println(o, " x y")
else
error("Incorrect dimensions of matrix passed to Patch2D")
end
for i in 1 : size(p.data, 2)
@printf(o, " %g %g", p.data[1,i], # x
p.data[2,i]) # y
if size(p.data, 1) > 2
@printf(o, " %g\n", p.data[3,i]) # color
else
println(o)
end
if mod(i, m) == 0
println(o) # extra space between patches (trainges or rectangles)
end
end
println(o, "};")
plotLegend(o, p.legendentry)
end
function plotHelper(o::IO, p::MatrixPlot)
if p.zmin >= p.zmax
error("Your colorbar range limits must not be equal to each other.")
end
plot_options = String["point meta min = $(p.zmin)", "point meta max = $(p.zmax)"]
if !(p.raster)
push!(plot_options, "point meta = explicit", "matrix plot*", "mesh/cols = $(p.cols)", "mesh/rows = $(p.rows)")
end
if !isnothing(p.style)
push!(plot_options, p.style)
end
print(o, "\\addplot[\n ")
print(o, join(plot_options, ",\n "))
print(o, "\n]")
if p.raster
print(o, " graphics[\n ")
println(o, join(["xmin = $(p.xmin)", "xmax = $(p.xmax)", "ymin = $(p.ymin)", "ymax = $(p.ymax)"], ",\n "))
println(o, "] {$(p.filename)};")
else
println(o, " table[\n meta = data\n] {$(p.filename)};")
end
end
# plot option string and contents; no \begin{axis} or \nextgroupplot
function plotHelper(o::IO, axis::Axis)
optionHelper(o, axisMap, axis; postOptions=cat(map(axisOptions, axis.plots)...; dims=1))
println(o, "\n") # empty line after options of \begin{axis}
for p in axis.plots
plotHelper(o, p)
try
if !isnothing(p.texlabel)
println(o, "\\label{$(p.texlabel)}")
end
catch
end
println(o) # empty line between plots
end
end
function tikzCode(axis::Axis)
o = IOBuffer()
print(o, "\\begin{$(axis.axisKeyword)}")
plotHelper(o, axis)
print(o, "\\end{$(axis.axisKeyword)}")
return String(take!(o))
end
function tikzCode(axes::Axes)
o = IOBuffer()
for axis in axes
print(o, "\\begin{$(axis.axisKeyword)}")
plotHelper(o, axis)
println(o, "\\end{$(axis.axisKeyword)}")
end
return String(take!(o))
end
plot(ax::Union{Axis,Axes}) =
TikzPicture(tikzCode(ax), options=pgfplotsoptions(), preamble=pgfplotspreamble())
function tikzCode(p::GroupPlot)
o = IOBuffer()
style = ""
if !isnothing(p.style)
style = p.style * ", "
end
groupStyle = ""
if !isnothing(p.groupStyle)
groupStyle = p.groupStyle * ", "
end
println(o, "\\begin{groupplot}[$(style)group style={$(groupStyle)group size=$(p.dimensions[1]) by $(p.dimensions[2])}]")
for a in p.axes
print(o, "\n\\nextgroupplot ")
plotHelper(o, a)
end
println(o, "\n\\end{groupplot}")
return String(take!(o))
end
function plot(p::GroupPlot)
mypreamble = pgfplotspreamble() * "\\usepgfplotslibrary{groupplots}"
TikzPicture(tikzCode(p), options=pgfplotsoptions(), preamble=mypreamble)
end
const Plottable = Union{Plot,GroupPlot,Axis,Axes,TikzPicture}
tikzCode(p::Plot) = tikzCode(Axis(p))
plot(p::Plot) = plot(Axis(p))
tikzCode(p::Contour) =
tikzCode(Axis(p, xmin=p.xbins[1], xmax=p.xbins[end], ymin=p.ybins[1], ymax=p.ybins[end]))
plot(p::Contour) =
plot(Axis(p, xmin=p.xbins[1], xmax=p.xbins[end], ymin=p.ybins[1], ymax=p.ybins[end]))
tikzCode(
x::AbstractArray{A,1},
y::AbstractArray{B,1};
kwargs...,
) where {A<:Real,B<:Real} = tikzCode(Linear(x, y; kwargs...))
plot(
x::AbstractArray{A,1},
y::AbstractArray{B,1};
kwargs...,
) where {A<:Real,B<:Real} = plot(Linear(x, y; kwargs...))
tikzCode(
x::AbstractVector{A},
y::AbstractVector{B},
z::AbstractVector{C};
kwargs...,
) where {A<:Real,B<:Real,C<:Real} = tikzCode(Linear3(x, y, z; kwargs...))
plot(
x::AbstractVector{A},
y::AbstractVector{B},
z::AbstractVector{C};
kwargs...,
) where {A<:Real,B<:Real,C<:Real} = plot(Linear3(x, y, z; kwargs...))
function Plots.Linear(f::Function, arg_range::RealRange; xbins=100, mark="none", kwargs...)
x = range(arg_range[1], stop=arg_range[2], length=xbins)
Linear(x, map(f, x); mark=mark, kwargs...)
end
tikzCode(f::Function, arg_range::RealRange; kwargs...) = tikzCode(Linear(f, arg_range; kwargs...))
plot(f::Function, arg_range::RealRange; kwargs...) = plot(Linear(f, arg_range; kwargs...))
plot(tkz::TikzPicture) = tkz # tikz pic doesn't need plot, here for convenience
Base.showable(::MIME"image/svg+xml", p::Plottable) = true
cleanup(p::Axis) = map(cleanup, p.plots)
cleanup(axes::Axes) = map(cleanup, axes)
cleanup(p::GroupPlot) = map(cleanup, p.axes)
cleanup(p::Plot) = nothing
cleanup(p::Circle) = nothing
cleanup(p::Ellipse) = nothing
cleanup(p::Command) = nothing
cleanup(p::Image) = rm(p.filename)
cleanup(p::MatrixPlot) = rm(p.filename)
cleanup(p::Contour) = nothing
cleanup(p::TikzPicture) = nothing
axisOptions(p::Plot) = String[]
function colormapOptions(cm::ColorMaps.GrayMap)
if cm.invert
return "colormap={wb}{gray(0cm)=(1); gray(1cm)=(0)}"
else
return "colormap={wb}{gray(0cm)=(0); gray(1cm)=(1)}"
end
end
function colormapOptions(cm::ColorMaps.RGBArrayMap)
o = IOBuffer()
print(o, "colormap={mycolormap}{ ")
n = length(cm.colors)
for i = 1:n
c = cm.colors[i]
print(o, "rgb($(i-1)cm)=($(c.r),$(c.g),$(c.b)) ")
end
print(o, "}")
String(take!(o))
end
function axisOptions(p::Image)
if p.colorbar
cmOpt = colormapOptions(p.colormap)
if isnothing(p.colorbarStyle)
return ["enlargelimits = false", "axis on top", cmOpt, "colorbar"]
else
return ["enlargelimits = false", "axis on top", cmOpt, "colorbar", "colorbar style = {$(p.colorbarStyle)}"]
end
else
return ["enlargelimits = false", "axis on top"]
end
end
function axisOptions(p::MatrixPlot)
if p.colorbar
cmOpt = colormapOptions(p.colormap)
options = ["enlargelimits = false", "axis on top", cmOpt, "colorbar", "xmin = $(p.xmin)", "xmax = $(p.xmax)", "ymin = $(p.ymin)", "ymax = $(p.ymax)"]
if !isnothing(p.colorbarStyle)
push!(options, "style = {$(p.colorbarStyle)}")
end
return options
else
return ["enlargelimits = false", "axis on top"]
end
end
canPlot(p::Axis) = all(map(canPlot, p.plots))
canPlot(axes::Axes) = all(map(canPlot, axes))
canPlot(p::GroupPlot) = all(map(canPlot, p.axes))
canPlot(p::Plot) = true
canPlot(p::Circle) = true
canPlot(p::Ellipse) = true
canPlot(p::Command) = true
canPlot(p::Image) = isfile(p.filename)
canPlot(p::MatrixPlot) = isfile(p.filename)
canPlot(p::Contour) = true
canPlot(p::TikzPicture) = true
function Base.show(f::IO, a::MIME"image/svg+xml", p::Plottable)
if canPlot(p)
r = Base.show(f, a, plot(p))
cleanup(p)
r
end
end
function save(filename::AbstractString, o::Plottable; include_preamble::Bool=true, limit_to::Symbol=:default)
_, ext = splitext(filename)
ext = lowercase(ext)
if ext == ".pdf"
save(PDF(filename), plot(o))
cleanup(o)
elseif ext == ".svg"
save(SVG(filename), plot(o))
cleanup(o)
elseif ext == ".tex"
# limit_to requires TikzPictures v3.2.0; only use if specified
if limit_to != :default
save(TEX(filename; limit_to=limit_to), plot(o))
else
save(TEX(filename, include_preamble=include_preamble), plot(o))
end
elseif ext == ".tikz"
# limit_to and include_preamble require TikzPictures v3.3.2; only use if not default
if limit_to != :default
save(TIKZ(filename; limit_to=limit_to), plot(o))
else
if !include_preamble
save(TIKZ(filename; include_preamble=include_preamble), plot(o))
else
save(TIKZ(filename), plot(o))
end
end
elseif ext == "." || ext == ""
error("You must specify a file extension.")
else
error("Unsupported file extensions: $ext")
end
end
end # module