forked from jheinen/GR.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jlgr.jl
2829 lines (2427 loc) · 81.6 KB
/
jlgr.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module jlgr
import GR
# These methods are extended in jlgr
import GR: hexbin, contour, contourf, surface
using Serialization
using Sockets
export
colormap,
figure,
gcf,
hold,
usecolorscheme,
subplot,
plot,
oplot,
semilogx,
semilogy,
loglog,
stairs,
scatter,
stem,
barplot,
histogram,
polarhistogram,
contour,
contourf,
hexbin,
heatmap,
heatmap,
polarheatmap,
nonuniformpolarheatmap,
wireframe,
surface,
volume,
plot3,
scatter3,
title,
redraw,
xlabel,
ylabel,
drawgrid,
xticks,
yticks,
zticks,
xticklabels,
yticklabels,
legend,
xlim,
ylim,
savefig,
meshgrid,
meshgrid,
peaks,
imshow,
isosurface,
cart2sph,
sph2cart,
polar,
trisurf,
tricont,
shade,
setpanzoom,
mainloop
function search(s::AbstractString, c::Char)
result = findfirst(isequal(c), s)
result !== nothing ? result : 0
end
signif(x, digits; base = 10) = round(x, sigdigits = digits, base = base)
macro _tuple(t)
:( Tuple{$t} )
end
const PlotArg = Union{AbstractString, AbstractVector, AbstractMatrix, Function}
const gr3 = GR.gr3
const plot_kind = [:line, :stairs, :scatter, :stem, :hist, :contour, :contourf, :hexbin, :heatmap, :nonuniformheatmap, :wireframe, :surface, :plot3, :scatter3, :imshow, :isosurface, :polar, :polarhist, :polarheatmap, :nonuniformpolarheatmap, :trisurf, :tricont, :shade, :volume]
const arg_fmt = [:xys, :xyac, :xyzc]
const kw_args = [:accelerate, :algorithm, :alpha, :backgroundcolor, :barwidth, :baseline, :clabels, :color, :colormap, :figsize, :font, :isovalue, :labels, :levels, :location, :nbins, :rotation, :size, :tilt, :title, :where, :xflip, :xform, :xlabel, :xlim, :xlog, :yflip, :ylabel, :ylim, :ylog, :zflip, :zlabel, :zlim, :zlog, :clim, :subplot, :linewidth, :grid]
const colors = [
[0xffffff, 0x000000, 0xff0000, 0x00ff00, 0x0000ff, 0x00ffff, 0xffff00, 0xff00ff] [0x282c34, 0xd7dae0, 0xcb4e42, 0x99c27c, 0x85a9fc, 0x5ab6c1, 0xd09a6a, 0xc57bdb] [0xfdf6e3, 0x657b83, 0xdc322f, 0x859900, 0x268bd2, 0x2aa198, 0xb58900, 0xd33682] [0x002b36, 0x839496, 0xdc322f, 0x859900, 0x268bd2, 0x2aa198, 0xb58900, 0xd33682]
]
const fonts = Dict(
"Times_Roman" => 101, "Times_Italic" => 102, "Times_Bold" => 103, "Times_BoldItalic" => 104,
"Helvetica_Regular" => 105, "Helvetica_Oblique" => 106, "Helvetica_Bold" => 107, "Helvetica_BoldOblique" => 108,
"Courier_Regular" => 109, "Courier_Oblique" => 110, "Courier_Bold" => 111, "Courier_BoldOblique" => 112,
"Symbol" => 113,
"Bookman_Light" => 114, "Bookman_LightItalic" => 115, "Bookman_Demi" => 116, "Bookman_DemiItalic" => 117,
"NewCenturySchlbk_Roman" => 118, "NewCenturySchlbk_Italic" => 119, "NewCenturySchlbk_Bold" => 120, "NewCenturySchlbk_BoldItalic" => 121,
"AvantGarde_Book" => 122, "AvantGarde_BookOblique" => 123, "AvantGarde_Demi" => 124, "AvantGarde_DemiOblique" => 125,
"Palatino_Roman" => 126, "Palatino_Italic" => 127, "Palatino_Bold" => 128, "Palatino_BoldItalic" => 129,
"ZapfChancery_MediumItalic" => 130,
"ZapfDingbats" => 131,
"CMUSerif-Math" => 232,
"DejaVuSans" => 233)
const distinct_cmap = [ 0, 1, 984, 987, 989, 983, 994, 988 ]
function linspace(start, stop, length)
range(start, stop=stop, length=length)
end
repmat(A::AbstractArray, m::Int, n::Int) = repeat(A::AbstractArray, m::Int, n::Int)
function _min(a)
minimum(filter(!isnan, a))
end
function _max(a)
maximum(filter(!isnan, a))
end
mutable struct PlotObject
obj
args
kvs
end
function Figure(width=600, height=450)
obj = Dict()
args = @_tuple(Any)
kvs = Dict()
kvs[:size] = (width, height)
kvs[:ax] = false
kvs[:subplot] = [0, 1, 0, 1]
kvs[:clear] = true
kvs[:update] = true
kvs[:panzoom] = nothing
PlotObject(obj, args, kvs)
end
function gcf()
plt.kvs
end
plt = Figure()
ctx = Dict()
scheme = 0
background = 0xffffff
handle = nothing
isrowvec(x::AbstractArray) = ndims(x) == 2 && size(x, 1) == 1 && size(x, 2) > 1
isvector(x::AbstractVector) = true
isvector(x::AbstractMatrix) = size(x, 1) == 1
function set_viewport(kind, subplot)
mwidth, mheight, width, height = GR.inqdspsize()
if haskey(plt.kvs, :figsize)
w = 0.0254 * width * plt.kvs[:figsize][1] / mwidth
h = 0.0254 * height * plt.kvs[:figsize][2] / mheight
else
dpi = width / mwidth * 0.0254
if dpi > 200
w, h = [x * dpi / 100 for x in plt.kvs[:size]]
else
w, h = plt.kvs[:size]
end
end
viewport = zeros(4)
vp = copy(float(subplot))
if w > h
ratio = float(h) / w
msize = mwidth * w / width
GR.setwsviewport(0, msize, 0, msize * ratio)
GR.setwswindow(0, 1, 0, ratio)
vp[3] *= ratio
vp[4] *= ratio
else
ratio = float(w) / h
msize = mheight * h / height
GR.setwsviewport(0, msize * ratio, 0, msize)
GR.setwswindow(0, ratio, 0, 1)
vp[1] *= ratio
vp[2] *= ratio
end
if kind in (:wireframe, :surface, :plot3, :scatter3, :trisurf, :volume)
extent = min(vp[2] - vp[1], vp[4] - vp[3])
vp1 = 0.5 * (vp[1] + vp[2] - extent)
vp2 = 0.5 * (vp[1] + vp[2] + extent)
vp3 = 0.5 * (vp[3] + vp[4] - extent)
vp4 = 0.5 * (vp[3] + vp[4] + extent)
else
vp1, vp2, vp3, vp4 = vp
end
left_margin = haskey(plt.kvs, :ylabel) ? 0.05 : 0
if kind in (:contour, :contourf, :hexbin, :heatmap, :nonuniformheatmap, :polarheatmap, :nonuniformpolarheatmap, :surface, :trisurf, :volume)
right_margin = (vp2 - vp1) * 0.1
else
right_margin = 0
end
bottom_margin = haskey(plt.kvs, :xlabel) ? 0.05 : 0
top_margin = haskey(plt.kvs, :title) ? 0.075 : 0
viewport[1] = vp1 + (0.075 + left_margin) * (vp2 - vp1)
viewport[2] = vp1 + (0.95 - right_margin) * (vp2 - vp1)
viewport[3] = vp3 + (0.075 + bottom_margin) * (vp4 - vp3)
viewport[4] = vp3 + (0.975 - top_margin) * (vp4 - vp3)
if kind in (:line, :stairs, :scatter, :stem) && haskey(plt.kvs, :labels)
location = get(plt.kvs, :location, 1)
if location in (11, 12, 13)
w, h = legend_size()
viewport[2] -= w + 0.1
end
end
GR.setviewport(viewport[1], viewport[2], viewport[3], viewport[4])
plt.kvs[:viewport] = viewport
plt.kvs[:vp] = vp
plt.kvs[:ratio] = ratio
if haskey(plt.kvs, :backgroundcolor)
GR.savestate()
GR.selntran(0)
GR.setfillintstyle(GR.INTSTYLE_SOLID)
GR.setfillcolorind(plt.kvs[:backgroundcolor])
if w > h
GR.fillrect(subplot[1], subplot[2],
ratio * subplot[3], ratio * subplot[4])
else
GR.fillrect(ratio * subplot[1], ratio * subplot[2],
subplot[3], subplot[4])
end
GR.selntran(1)
GR.restorestate()
end
if kind in (:polar, :polarhist, :polarheatmap, :nonuniformpolarheatmap)
xmin, xmax, ymin, ymax = viewport
xcenter = 0.5 * (xmin + xmax)
ycenter = 0.5 * (ymin + ymax)
r = 0.5 * min(xmax - xmin, ymax - ymin)
GR.setviewport(xcenter - r, xcenter + r, ycenter - r, ycenter + r)
end
end
function fix_minmax(a, b)
if a == b
a -= a != 0 ? 0.1 * a : 0.1
b += b != 0 ? 0.1 * b : 0.1
end
a, b
end
function given(a)
a != Nothing && a != "Nothing"
end
function Extrema64(a)
amin = typemax(Float64)
amax = -typemax(Float64)
for el in a
if !isnan(el)
if isnan(amin) || el < amin
amin = el
end
if isnan(amax) || el > amax
amax = el
end
end
end
amin, amax
end
function minmax(kind)
xmin = ymin = zmin = cmin = typemax(Float64)
xmax = ymax = zmax = cmax = -typemax(Float64)
scale = plt.kvs[:scale]
for (x, y, z, c, spec) in plt.args
if given(x)
if scale & GR.OPTION_X_LOG != 0
x = map(v -> v>0 ? v : NaN, x)
end
x0, x1 = Extrema64(x)
xmin = min(x0, xmin)
xmax = max(x1, xmax)
elseif kind == :volume
xmin, xmax = -1, 1
else
xmin, xmax = 0, 1
end
if given(y)
if scale & GR.OPTION_Y_LOG != 0
y = map(v -> v>0 ? v : NaN, y)
end
y0, y1 = Extrema64(y)
ymin = min(y0, ymin)
ymax = max(y1, ymax)
elseif kind == :volume
ymin, ymax = -1, 1
else
ymin, ymax = 0, 1
end
if given(z)
if scale & GR.OPTION_Z_LOG != 0
z = map(v -> v>0 ? v : NaN, z)
end
z0, z1 = Extrema64(z)
zmin = min(z0, zmin)
zmax = max(z1, zmax)
end
if given(c)
c0, c1 = Extrema64(c)
cmin = min(c0, cmin)
cmax = max(c1, cmax)
elseif given(z)
c0, c1 = Extrema64(z)
cmin = min(c0, cmin)
cmax = max(c1, cmax)
end
end
xmin, xmax = fix_minmax(xmin, xmax)
ymin, ymax = fix_minmax(ymin, ymax)
zmin, zmax = fix_minmax(zmin, zmax)
if haskey(plt.kvs, :xlim)
x0, x1 = plt.kvs[:xlim]
if x0 === Nothing x0 = xmin end
if x1 === Nothing x1 = xmax end
plt.kvs[:xrange] = (x0, x1)
else
plt.kvs[:xrange] = xmin, xmax
end
if haskey(plt.kvs, :ylim)
y0, y1 = plt.kvs[:ylim]
if y0 === Nothing y0 = ymin end
if y1 === Nothing y1 = ymax end
plt.kvs[:yrange] = (y0, y1)
else
plt.kvs[:yrange] = ymin, ymax
end
if haskey(plt.kvs, :zlim)
z0, z1 = plt.kvs[:zlim]
if z0 === Nothing z0 = zmin end
if z1 === Nothing z1 = zmax end
plt.kvs[:zrange] = (z0, z1)
else
plt.kvs[:zrange] = zmin, zmax
end
if haskey(plt.kvs, :clim)
c0, c1 = plt.kvs[:clim]
if c0 === Nothing c0 = cmin end
if c1 === Nothing c1 = cmax end
plt.kvs[:crange] = (c0, c1)
else
plt.kvs[:crange] = cmin, cmax
end
end
function to_wc(wn)
xmin, ymin = GR.ndctowc(wn[1], wn[3])
xmax, ymax = GR.ndctowc(wn[2], wn[4])
xmin, xmax, ymin, ymax
end
fract(x) = modf(x)[1]
function auto_tick(amin, amax)
scale = 10.0 ^ trunc(log10(amax - amin))
tick_size = (5.0, 2.0, 1.0, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01)
tick = 1.0
for i in 1:length(tick_size)
n = (amax - amin) / scale / tick_size[i]
if n > 7
tick = tick_size[i - 1]
break
end
end
tick *= scale
end
function set_window(kind)
scale = 0
if !(kind in (:polar, :polarhist, :polarheatmap, :nonuniformpolarheatmap))
get(plt.kvs, :xlog, false) && (scale |= GR.OPTION_X_LOG)
get(plt.kvs, :ylog, false) && (scale |= GR.OPTION_Y_LOG)
get(plt.kvs, :zlog, false) && (scale |= GR.OPTION_Z_LOG)
get(plt.kvs, :xflip, false) && (scale |= GR.OPTION_FLIP_X)
get(plt.kvs, :yflip, false) && (scale |= GR.OPTION_FLIP_Y)
get(plt.kvs, :zflip, false) && (scale |= GR.OPTION_FLIP_Z)
end
plt.kvs[:scale] = scale
if plt.kvs[:panzoom] !== nothing
xmin, xmax, ymin, ymax = GR.panzoom(plt.kvs[:panzoom]...)
plt.kvs[:xrange] = (xmin, xmax)
plt.kvs[:yrange] = (ymin, ymax)
else
minmax(kind)
end
if kind in (:wireframe, :surface, :plot3, :scatter3, :polar, :polarhist, :polarheatmap, :nonuniformpolarheatmap, :trisurf, :volume)
major_count = 2
else
major_count = 5
end
xmin, xmax = plt.kvs[:xrange]
if kind in (:heatmap, :polarheatmap) && !haskey(plt.kvs, :xlim)
xmin -= 0.5
xmax += 0.5
end
if scale & GR.OPTION_X_LOG == 0
if !haskey(plt.kvs, :xlim) && plt.kvs[:panzoom] === nothing && !(kind in (:heatmap, :polarheatmap, :nonuniformpolarheatmap))
xmin, xmax = GR.adjustlimits(xmin, xmax)
end
if haskey(plt.kvs, :xticks)
xtick, majorx = plt.kvs[:xticks]
else
majorx = major_count
xtick = auto_tick(xmin, xmax) / major_count
end
else
xtick = majorx = 1
end
if scale & GR.OPTION_FLIP_X == 0
xorg = (xmin, xmax)
else
xorg = (xmax, xmin)
end
plt.kvs[:xaxis] = xtick, xorg, majorx
ymin, ymax = plt.kvs[:yrange]
if kind in (:heatmap, :polarheatmap) && !haskey(plt.kvs, :ylim)
ymin -= 0.5
ymax += 0.5
end
if kind == :hist && !haskey(plt.kvs, :ylim)
ymin = scale & GR.OPTION_Y_LOG == 0 ? 0 : 1
end
if scale & GR.OPTION_Y_LOG == 0
if !haskey(plt.kvs, :ylim) && plt.kvs[:panzoom] === nothing && !(kind in (:heatmap, :polarheatmap, :nonuniformpolarheatmap))
ymin, ymax = GR.adjustlimits(ymin, ymax)
end
if haskey(plt.kvs, :yticks)
ytick, majory = plt.kvs[:yticks]
else
majory = major_count
ytick = auto_tick(ymin, ymax) / major_count
end
else
ytick = majory = 1
end
if scale & GR.OPTION_FLIP_Y == 0
yorg = (ymin, ymax)
else
yorg = (ymax, ymin)
end
plt.kvs[:yaxis] = ytick, yorg, majory
if kind in (:wireframe, :surface, :plot3, :scatter3, :trisurf, :volume)
zmin, zmax = plt.kvs[:zrange]
if scale & GR.OPTION_Z_LOG == 0
if !haskey(plt.kvs, :zlim)
zmin, zmax = GR.adjustlimits(zmin, zmax)
end
if haskey(plt.kvs, :zticks)
ztick, majorz = plt.kvs[:zticks]
else
majorz = major_count
ztick = auto_tick(zmin, zmax) / major_count
end
else
ztick = majorz = 1
end
if scale & GR.OPTION_FLIP_Z == 0
zorg = (zmin, zmax)
else
zorg = (zmax, zmin)
end
plt.kvs[:zaxis] = ztick, zorg, majorz
end
plt.kvs[:window] = xmin, xmax, ymin, ymax
if !(kind in (:polar, :polarhist, :polarheatmap, :nonuniformpolarheatmap, :trisurf))
GR.setwindow(xmin, xmax, ymin, ymax)
else
GR.setwindow(-1, 1, -1, 1)
end
if kind in (:wireframe, :surface, :plot3, :scatter3, :trisurf, :volume)
rotation = get(plt.kvs, :rotation, 40)
tilt = get(plt.kvs, :tilt, 60)
GR.setwindow3d(xmin, xmax, ymin, ymax, zmin, zmax)
GR.setspace3d(-rotation, tilt, 30, 0)
end
plt.kvs[:scale] = scale
GR.setscale(scale)
end
function ticklabel_fun(f::Function)
return (x, y, svalue, value) -> GR.textext(x, y, string(f(value)))
end
function ticklabel_fun(labels::AbstractVecOrMat{T}) where T <: AbstractString
(x, y, svalue, value) -> begin
pos = findfirst(t->(value≈t), collect(1:length(labels)))
lab = (pos === nothing) ? "" : labels[pos]
GR.textext(x, y, lab)
end
end
function draw_axes(kind, pass=1)
viewport = plt.kvs[:viewport]
vp = plt.kvs[:vp]
ratio = plt.kvs[:ratio]
xtick, xorg, majorx = plt.kvs[:xaxis]
ytick, yorg, majory = plt.kvs[:yaxis]
drawgrid = get(plt.kvs, :grid, true)
# enforce scientific notation for logarithmic axes labels
if plt.kvs[:scale] & GR.OPTION_X_LOG != 0
xtick = 10
end
if plt.kvs[:scale] & GR.OPTION_Y_LOG != 0
ytick = 10
end
GR.setlinecolorind(1)
diag = sqrt((viewport[2] - viewport[1])^2 + (viewport[4] - viewport[3])^2)
GR.setlinewidth(1)
ticksize = 0.0075 * diag
if kind in (:wireframe, :surface, :plot3, :scatter3, :trisurf, :volume)
charheight = max(0.024 * diag, 0.012)
GR.setcharheight(charheight)
ztick, zorg, majorz = plt.kvs[:zaxis]
if pass == 1 && drawgrid
GR.grid3d(xtick, 0, ztick, xorg[1], yorg[2], zorg[1], 2, 0, 2)
GR.grid3d(0, ytick, 0, xorg[1], yorg[2], zorg[1], 0, 2, 0)
else
GR.axes3d(xtick, 0, ztick, xorg[1], yorg[1], zorg[1], majorx, 0, majorz, -ticksize)
GR.axes3d(0, ytick, 0, xorg[2], yorg[1], zorg[1], 0, majory, 0, ticksize)
end
else
charheight = max(0.018 * diag, 0.012)
GR.setcharheight(charheight)
if kind in (:heatmap, :nonuniformheatmap, :shade)
ticksize = -ticksize
else
drawgrid && GR.grid(xtick, ytick, 0, 0, majorx, majory)
end
if haskey(plt.kvs, :xticklabels) || haskey(plt.kvs, :yticklabels)
fx = get(plt.kvs, :xticklabels, identity) |> ticklabel_fun
fy = get(plt.kvs, :yticklabels, identity) |> ticklabel_fun
GR.axeslbl(xtick, ytick, xorg[1], yorg[1], majorx, majory, ticksize, fx, fy)
else
GR.axes(xtick, ytick, xorg[1], yorg[1], majorx, majory, ticksize)
end
GR.axes(xtick, ytick, xorg[2], yorg[2], -majorx, -majory, -ticksize)
end
if haskey(plt.kvs, :title)
GR.savestate()
GR.settextalign(GR.TEXT_HALIGN_CENTER, GR.TEXT_VALIGN_TOP)
text(0.5 * (viewport[1] + viewport[2]), vp[4], plt.kvs[:title])
GR.restorestate()
end
if kind in (:wireframe, :surface, :plot3, :scatter3, :trisurf, :volume)
xlabel = get(plt.kvs, :xlabel, "")
ylabel = get(plt.kvs, :ylabel, "")
zlabel = get(plt.kvs, :zlabel, "")
GR.titles3d(xlabel, ylabel, zlabel)
else
if haskey(plt.kvs, :xlabel)
GR.savestate()
GR.settextalign(GR.TEXT_HALIGN_CENTER, GR.TEXT_VALIGN_BOTTOM)
text(0.5 * (viewport[1] + viewport[2]), vp[3] + 0.5 * charheight, plt.kvs[:xlabel])
GR.restorestate()
end
if haskey(plt.kvs, :ylabel)
GR.savestate()
GR.settextalign(GR.TEXT_HALIGN_CENTER, GR.TEXT_VALIGN_TOP)
GR.setcharup(-1, 0)
text(vp[1] + 0.5 * charheight, 0.5 * (viewport[3] + viewport[4]), plt.kvs[:ylabel])
GR.restorestate()
end
end
end
function draw_polar_axes()
viewport = plt.kvs[:viewport]
diag = sqrt((viewport[2] - viewport[1])^2 + (viewport[4] - viewport[3])^2)
charheight = max(0.018 * diag, 0.012)
window = plt.kvs[:window]
rmin, rmax = window[3], window[4]
GR.savestate()
GR.setcharheight(charheight)
GR.setlinetype(GR.LINETYPE_SOLID)
tick = auto_tick(rmin, rmax)
n = trunc(Int, (rmax - rmin) / tick)
for i in 0:n
r = rmin + i * tick / (rmax - rmin)
if i % 2 == 0
GR.setlinecolorind(88)
if i > 0
GR.drawarc(-r, r, -r, r, 0, 359)
end
GR.settextalign(GR.TEXT_HALIGN_LEFT, GR.TEXT_VALIGN_HALF)
x, y = GR.wctondc(0.05, r)
GR.text(x, y, string(signif(rmin + i * tick, 12)))
else
GR.setlinecolorind(90)
GR.drawarc(-r, r, -r, r, 0, 359)
end
end
for alpha in 0:45:315
sinf = sin(alpha * π / 180)
cosf = cos(alpha * π / 180)
GR.polyline([cosf, 0], [sinf, 0])
GR.settextalign(GR.TEXT_HALIGN_CENTER, GR.TEXT_VALIGN_HALF)
x, y = GR.wctondc(1.1 * cosf, 1.1 * sinf)
GR.textext(x, y, string(alpha, "^o"))
end
GR.restorestate()
end
function inqtext(x, y, s)
if length(s) >= 2 && s[1] == '$' && s[end] == '$'
GR.inqmathtex(x, y, s[2:end-1])
elseif search(s, '\\') != 0 || search(s, '_') != 0 || search(s, '^') != 0
GR.inqtextext(x, y, s)
else
GR.inqtext(x, y, s)
end
end
function text(x, y, s)
if length(s) >= 2 && s[1] == '$' && s[end] == '$'
GR.mathtex(x, y, s[2:end-1])
elseif search(s, '\\') != 0 || search(s, '_') != 0 || search(s, '^') != 0
GR.textext(x, y, s)
else
GR.text(x, y, s)
end
end
function legend_size()
scale = Int(GR.inqscale())
GR.selntran(0)
GR.setscale(0)
w = 0
h = 0
for label in plt.kvs[:labels]
tbx, tby = inqtext(0, 0, label)
w = max(w, tbx[3] - tbx[1])
h += max(tby[3] - tby[1], 0.03)
end
GR.setscale(scale)
GR.selntran(1)
w, h
end
hasline(mask) = ( mask == 0x00 || (mask & 0x01 != 0) )
hasmarker(mask) = ( mask & 0x02 != 0)
function draw_legend()
w, h = legend_size()
viewport = plt.kvs[:viewport]
location = get(plt.kvs, :location, 1)
num_labels = length(plt.kvs[:labels])
GR.savestate()
GR.selntran(0)
GR.setscale(0)
if location in (11, 12, 13)
px = viewport[2] + 0.11
elseif location in (8, 9, 10)
px = 0.5 * (viewport[1] + viewport[2] - w + 0.05)
elseif location in (2, 3, 6)
px = viewport[1] + 0.11
else
px = viewport[2] - 0.05 - w
end
if location in (5, 6, 7, 10, 12)
py = 0.5 * (viewport[3] + viewport[4] + h - 0.03)
elseif location == 13
py = viewport[3] + h
elseif location in (3, 4, 8)
py = viewport[3] + h + 0.03
elseif location == 11
py = viewport[4] - 0.03
else
py = viewport[4] - 0.06
end
GR.setfillintstyle(GR.INTSTYLE_SOLID)
GR.setfillcolorind(0)
GR.fillrect(px - 0.08, px + w + 0.02, py + 0.03, py - h)
GR.setlinetype(GR.LINETYPE_SOLID)
GR.setlinecolorind(1)
GR.setlinewidth(1)
GR.drawrect(px - 0.08, px + w + 0.02, py + 0.03, py - h)
i = 1
GR.uselinespec(" ")
for (x, y, z, c, spec) in plt.args
if i <= num_labels
label = plt.kvs[:labels][i]
tbx, tby = inqtext(0, 0, label)
dy = max((tby[3] - tby[1]) - 0.03, 0)
py -= 0.5 * dy
end
GR.savestate()
mask = GR.uselinespec(spec)
hasline(mask) && GR.polyline([px - 0.07, px - 0.01], [py, py])
hasmarker(mask) && GR.polymarker([px - 0.06, px - 0.02], [py, py])
GR.restorestate()
GR.settextalign(GR.TEXT_HALIGN_LEFT, GR.TEXT_VALIGN_HALF)
if i <= num_labels
text(px, py, label)
py -= 0.5 * dy
i += 1
end
py -= 0.03
end
GR.selntran(1)
GR.restorestate()
end
function colorbar(off=0, colors=256)
GR.savestate()
viewport = plt.kvs[:viewport]
zmin, zmax = plt.kvs[:zrange]
mask = (GR.OPTION_Z_LOG | GR.OPTION_FLIP_Y | GR.OPTION_FLIP_Z)
if get(plt.kvs, :zflip, false)
options = (GR.inqscale() | GR.OPTION_FLIP_Y)
GR.setscale(options & mask)
elseif get(plt.kvs, :yflip, false)
options = GR.inqscale() & ~GR.OPTION_FLIP_Y
GR.setscale(options & mask)
else
options = GR.inqscale()
GR.setscale(options & mask)
end
h = 0.5 * (zmax - zmin) / (colors - 1)
GR.setwindow(0, 1, zmin, zmax)
GR.setviewport(viewport[2] + 0.02 + off, viewport[2] + 0.05 + off,
viewport[3], viewport[4])
l = zeros(Int32, 1, colors)
l[1,:] = Int[round(Int, _i) for _i in linspace(1000, 1255, colors)]
GR.cellarray(0, 1, zmax + h, zmin - h, 1, colors, l)
GR.setlinecolorind(1)
diag = sqrt((viewport[2] - viewport[1])^2 + (viewport[4] - viewport[3])^2)
charheight = max(0.016 * diag, 0.012)
GR.setcharheight(charheight)
if plt.kvs[:scale] & GR.OPTION_Z_LOG == 0
ztick = auto_tick(zmin, zmax)
GR.axes(0, ztick, 1, zmin, 0, 1, 0.005)
else
GR.setscale(GR.OPTION_Y_LOG)
GR.axes(0, 2, 1, zmin, 0, 1, 0.005)
end
GR.restorestate()
end
function colormap()
rgb = zeros(256, 3)
for colorind in 1:256
color = GR.inqcolor(999 + colorind)
rgb[colorind, 1] = float( color & 0xff) / 255.0
rgb[colorind, 2] = float((color >> 8) & 0xff) / 255.0
rgb[colorind, 3] = float((color >> 16) & 0xff) / 255.0
end
rgb
end
function to_rgba(value, cmap)
if !isnan(value)
r, g, b = cmap[round(Int, value * 255 + 1), :]
a = 1.0
else
r, g, b, a = zeros(4)
end
round(UInt32, a * 255) << 24 + round(UInt32, b * 255) << 16 +
round(UInt32, g * 255) << 8 + round(UInt32, r * 255)
end
function create_context(kind::Symbol, dict=plt.kvs)
plt.kvs[:kind] = kind
create_context(dict)
end
function create_context(dict::AbstractDict)
plt.obj = copy(plt.kvs)
for (k, v) in dict
if ! (k in kw_args)
println("Invalid keyword: $k")
end
end
merge!(plt.kvs, dict)
end
function restore_context()
global ctx
ctx = copy(plt.kvs)
plt.kvs = copy(plt.obj)
end
"""
Create a new figure with the given settings.
Settings like the current colormap, title or axis limits as stored in the
current figure. This function creates a new figure, restores the default
settings and applies any settings passed to the function as keyword
arguments.
**Usage examples:**
.. code-block:: julia
julia> # Restore all default settings
julia> figure()
julia> # Restore all default settings and set the title
julia> figure(title="Example Figure")
"""
function figure(; kv...)
global plt
plt = Figure()
merge!(plt.kvs, Dict(kv))
plt
end
"""
Set the hold flag for combining multiple plots.
The hold flag prevents drawing of axes and clearing of previous plots, so
that the next plot will be drawn on top of the previous one.
:param flag: the value of the hold flag
**Usage examples:**
.. code-block:: julia
julia> # Create example data
julia> x = LinRange(0, 1, 100)
julia> # Draw the first plot
julia> plot(x, x.^2)
julia> # Set the hold flag
julia> hold(true)
julia> # Draw additional plots
julia> plot(x, x.^4)
julia> plot(x, x.^8)
julia> # Reset the hold flag
julia> hold(false)
"""
function hold(flag)
global ctx
if plt.args != @_tuple(Any)
plt.kvs[:ax] = flag
plt.kvs[:clear] = !flag
for k in (:window, :scale, :xaxis, :yaxis, :zaxis)
if haskey(ctx, k)
plt.kvs[k] = ctx[k]
end
end
else
println("Invalid hold state")
end
flag
end
function usecolorscheme(index)
global scheme
if 1 <= index <= 4
scheme = index
else
println("Invalid color sheme")
end
end
"""
Set current subplot index.
By default, the current plot will cover the whole window. To display more
than one plot, the window can be split into a number of rows and columns,
with the current plot covering one or more cells in the resulting grid.
Subplot indices are one-based and start at the upper left corner, with a
new row starting after every **num_columns** subplots.
:param num_rows: the number of subplot rows
:param num_columns: the number of subplot columns
:param subplot_indices:
- the subplot index to be used by the current plot
- a pair of subplot indices, setting which subplots should be covered
by the current plot
**Usage examples:**
.. code-block:: julia
julia> # Set the current plot to the second subplot in a 2x3 grid
julia> subplot(2, 3, 2)
julia> # Set the current plot to cover the first two rows of a 4x2 grid
julia> subplot(4, 2, (1, 4))
julia> # Use the full window for the current plot
julia> subplot(1, 1, 1)
"""
function subplot(nr, nc, p)
xmin, xmax, ymin, ymax = 1, 0, 1, 0
for i in collect(p)
r = nr - div(i-1, nc)
c = (i-1) % nc + 1
xmin = min(xmin, (c-1)/nc)
xmax = max(xmax, c/nc)
ymin = min(ymin, (r-1)/nr)
ymax = max(ymax, r/nr)
end
plt.kvs[:subplot] = [xmin, xmax, ymin, ymax]
plt.kvs[:clear] = collect(p)[1] == 1
plt.kvs[:update] = collect(p)[end] == nr * nc
end
"""
Set the flag to draw a grid in the plot axes.
:param flag: the value of the grid flag (`true` by default)
**Usage examples:**
.. code-block:: julia
julia> # Hid the grid on the next plot
julia> grid(false)
julia> # Restore the grid
julia> grid(true)
"""
drawgrid(flag) = (plt.kvs[:grid] = flag)
const doc_ticks = """
Set the intervals of the ticks for the X, Y or Z axis.
Use the function `xticks`, `yticks` or `zticks` for the corresponding axis.
:param minor: the interval between minor ticks.
:param major: (optional) the number of minor ticks between major ticks.
**Usage examples:**
.. code-block:: julia
julia> # Minor ticks every 0.2 units in the X axis
julia> xticks(0.2)
julia> # Major ticks every 1 unit (5 minor ticks) in the Y axis
julia> yticks(0.2, 5)
"""
@doc doc_ticks xticks(minor, major::Int=1) = (plt.kvs[:xticks] = (minor, major))
@doc doc_ticks yticks(minor, major::Int=1) = (plt.kvs[:yticks] = (minor, major))
@doc doc_ticks zticks(minor, major::Int=1) = (plt.kvs[:zticks] = (minor, major))
const doc_ticklabels = """
Customize the string of the X and Y axes tick labels.
The labels of the tick axis can be defined through a function
with one argument (the numeric value of the tick position) and
returns a string, or through an array of strings that are located
sequentially at X = 1, 2, etc.
:param s: function or array of strings that define the tick labels.
**Usage examples:**
.. code-block:: julia
julia> # Label the range (0-1) of the Y-axis as percent values
julia> yticklabels(p -> Base.Printf.@sprintf("%0.0f%%", 100p))
julia> # Label the X-axis with a sequence of strings
julia> xticklabels(["first", "second", "third"])
"""
@doc doc_ticklabels xticklabels(s) = (plt.kvs[:xticklabels] = s)
@doc doc_ticklabels yticklabels(s) = (plt.kvs[:yticklabels] = s)
# Normalize a color c with the range [cmin, cmax]
# 0 <= normalize_color(c, cmin, cmax) <= 1
function normalize_color(c, cmin, cmax)
c = clamp(float(c), cmin, cmax) - cmin
if cmin != cmax
c /= cmax - cmin
end
c
end
function plot_img(I)
viewport = plt.kvs[:vp][:]
if haskey(plt.kvs, :title)
viewport[4] -= 0.05
end
vp = plt.kvs[:vp]
if isa(I, AbstractString)
width, height, data = GR.readimage(I)