-
Notifications
You must be signed in to change notification settings - Fork 1
/
plot.go
1384 lines (1204 loc) · 40 KB
/
plot.go
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
package plot
import (
"fmt"
"image/color"
"math"
"os"
"sort"
"strings"
"time"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/vgimg"
)
var now = time.Now
var col = color.RGBA{}
var floor = math.Floor
var _ = os.Open
// Plot represents a whole plot.
type Plot struct {
// The title of the plot.
Title string
// Data is the data to draw. If nil all layers must provide their
// own data.
Data *DataFrame
// Faceting describes the used Faceting.
Faceting Faceting
// Mapping describes how fieleds in data are mapped to Aesthetics.
Aes AesMapping
// Layers contains all the layers displayed in the plot.
Layers []*Layer
// Scales can be used to set up non-default scales, e.g.
// scales with a transformation or manualy set breaks.
//
// The scales of plot are distributed to the individual panels
// only and are not used directly as scales.
Scales map[string]*Scale
// Panels are the different panels for faceting.
Panels [][]*Panel
// Theme contains the visual defaults to use when drawing things.
Theme Theme
// Layout maps components like "Title" or "Y-Label" to their viewport.
Viewports map[string]Viewport
// Pool is the string pool used to keep the string-float64 mapping
Pool *StringPool
// Grobs contains the handful of plot (not part of panels) of
// graphical objects.
Grobs map[string]Grob
constructed bool
// ugly hack to save dimensions of plot visuals between rendering
// and layouting...
renderInfo map[string]vg.Length
}
// NewPlot creates a new plot. Data must be a SOM or a COS and aesthetics
// maps fields in data to plot aesthetics.
func NewPlot(data interface{}, aesthetics AesMapping) (*Plot, error) {
pool := NewStringPool()
df, err := NewDataFrameFrom(data, pool)
if err != nil {
return nil, err
}
if aesthetics == nil {
aesthetics = make(AesMapping)
}
plot := Plot{
Data: df,
Faceting: Faceting{},
Aes: aesthetics,
Layers: nil,
Scales: make(map[string]*Scale),
Panels: nil,
Theme: DefaultTheme,
Pool: pool,
Grobs: make(map[string]Grob),
constructed: false,
renderInfo: make(map[string]vg.Length),
}
return &plot, nil
}
// Compute facets the plot data, computes the statistics, constructs the
// geoms, scales the axes and prepares everything for rendering the plot.
func (plot *Plot) Compute() {
plot.CreatePanels()
for r := range plot.Panels {
for c := range plot.Panels[r] {
panel := plot.Panels[r][c]
// Prepare data: map aestetics, add scales, clean data frame and
// apply scale transformations. Mapped scales are pre-trained.
// Step 2
panel.PrepareData()
// The second step: Compute statistics.
// If a layer has a statistical transform: Apply this transformation
// to the data frame of this layer.
// Step 3
panel.ComputeStatistics()
// Make sure the output of the stat matches the input expected
// by the geom.
// Step 4
panel.WireStatToGeom()
// Construct geoms
// Apply geom specific position adjustments, train the involved
// scales and produce a set of fundamental geoms.
// Step 5
panel.ConstructGeoms()
}
}
for r := range plot.Panels {
for _, panel := range plot.Panels[r] {
// Finalize scales: Setup remaining fields.
// This can be done only after each panel completed
// the steps 2-5 ConstructGeoms which might change
// the scales.
// Step 6
panel.FinalizeScales()
}
}
for r := range plot.Panels {
for _, panel := range plot.Panels[r] {
// Render the fundamental Geoms to Grobs using scales.
// Step 7
panel.RenderGeoms()
}
}
// Render rest of elements (guides, titels, factting, ...)
// Step 8
plot.RenderVisuals()
plot.constructed = true
}
// DumpTo will render plot to canvas. The size of the generetad plot is
// determined by width and height.
func (plot *Plot) DumpTo(canvas vg.Canvas, width, height vg.Length) {
if !plot.constructed {
plot.Compute()
}
// Layouting the plot determines the viewports of all the elements
// in the plot, especially the panels.
plot.Layout(canvas, width, height)
// Actual drawing of the general stuff.
for _, element := range []string{"Title", "X-Label", "Y-Label", "Guides"} {
if grob, ok := plot.Grobs[element]; ok {
grob.Draw(plot.Viewports[element])
}
}
// Drawing of the individual panels.
showX, showY := false, false
for r := range plot.Panels {
showX = r == 0
for c, panel := range plot.Panels[r] {
showY = c == 0
panelId := fmt.Sprintf("Panel-%d,%d", r, c)
panel.Draw(plot.Viewports[panelId], showX, showY)
}
}
}
// WritePNG renders plot to a png file of size width x height.
func (p *Plot) WritePNG(filename string, width, height vg.Length) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
canvas := vgimg.PngCanvas{Canvas: vgimg.New(width, height)}
// canvas.Translate(vg.Point{-width / 2, -height / 2})
p.DumpTo(canvas, width, height)
canvas.WriteTo(file)
return nil
}
// Warnf prints args formated by f. TODO: proper error handling?
func (p *Plot) Warnf(f string, args ...interface{}) {
if !strings.HasSuffix(f, "\n") {
f = f + "\n"
}
fmt.Printf("Warning "+f, args...)
}
// -------------------------------------------------------------------------
// Layers, Panels and Faceting
// Layer represents one layer of data in a plot.
type Layer struct {
// The Name of the layer used used in printing.
Name string
// Panel is the Panal this Layer belogs to.
Panel *Panel
// A nil Data will use the Data from the plot this layer belongs to.
Data *DataFrame
// DataMapping is combined with the plot's AesMapping and used to
// map fields in Data to aesthetics.
// TODO: Why not name it AesMapping like in Plot?
DataMapping AesMapping
// Stat is the statistical transformation used in this layer.
// A nil stat is the identity transformation.
Stat Stat
// StatMapping is used to map new (i.e. generated by the stat) fields
// to plot aesthetics.
StatMapping AesMapping
// Geom is the geom to use for this layer.
Geom Geom
// GeomMapping is used to wire fields output by the statistical
// transform to the input fields used by the geom.
GeomMapping AesMapping
// The fundamental geoms to draw.
Fundamentals []Fundamental
// Grobs contains the graphical object after drawing.
Grobs []Grob
}
// A Panel is one panel, typically in a facetted plot.
// It does not differ much from a Plot as it actually represents
// one of the plots in a facetted plot.
type Panel struct {
// Name of the Panel
Name string
// The plot this panel belongs to
Plot *Plot
// Data is the data to draw.
Data *DataFrame
// Mapping, describes how fieleds in data are mapped to Aesthetics.
Aes AesMapping
// Layers contains all the layers displayed in the plot.
Layers []*Layer
// Scales contains the scales for this panel. Normaly all panels
// share all scales, but x and y might be free on faceted plots.
Scales map[string]*Scale
// The viewport this panel will be draw to.
Viewport Viewport
// Grobs contains the non-layer grobs like panel background
// and grid lines.
Grobs []Grob
// Top, Right, Buttom and Left viewports and grobs.
// Used for axis and strips.
// TODO: a bit ugly...
Tvp, Rvp, Bvp, Lvp Viewport
Tgr, Rgr, Bgr, Lgr []Grob
}
// Facetting describes the facetting to use. The zero value indicates
// no facetting.
type Faceting struct {
// Columns and Rows are the faceting specification. Each may be a
// field in the Data. An empty string means no faceting in this
// dimension.
Columns, Rows string
// Totals controlls display of row and column totals.
Totals bool // TODO: fancier control needed
// FreeScale determines which scales are free i.e. not shared
// between rows and/or columns:
// "" all scales shared
// "x" x is free (might be different on each column)
// "y" y is free (might be different on each row)
// "xy" both x and y are free
// (This is different from ggplot2. Here each row will share a common
// x-sclae and each row will share a common y-scale.)
FreeScale string
// FreeSpace determines which dimension of a panel has fixed
// size and which are free on a per row and/or column base.
// Arguments like FreeScale. BUG: Currently not implemented.
FreeSpace string
// ColStrips and RowStrips contain the strip labels.
// TODO: decide how to set manually.
ColStrips, RowStrips []string
}
// Fundamental is a simple geometrical object.
type Fundamental struct {
// Geom is one if the few fundamental Geoms.
Geom Geom
// Data is the data for the fundamental geom.
Data *DataFrame
}
// -------------------------------------------------------------------------
// Step 2: Preparing Data and Scales
// PrepareData is the first step in generating a plot.
// After preparing the data frame the following holds:
// - Layer has a own data frame (maybe a copy of plots data frame).
// - This data frame has no unused (aka not mapped to aesthetics)
// columns.
// - The columns name are the aestectics (e.g. x, y, size, color...)
// - The columns have been transformed according to the
// ScaleTransform associated with x, y, size, ....
//
// TODO: how about grouping? 69b0d2b contains grouping code.
//
// Step 2 in design.
func (panel *Panel) PrepareData() {
fmt.Printf("Panel %q: PrepareData()\n", panel.Name)
for i, layer := range panel.Layers {
fmt.Printf(" Layer %d %q: PrepareData()\n", i, layer.Name)
// Step 2a
// Set up data and aestetics mapping.
if layer.Data == nil {
layer.Data = layer.Panel.Data.Copy()
}
aes := MergeAes(layer.DataMapping, layer.Panel.Plot.Aes)
// Drop all unused (unmapped) fields in the data frame.
_, fields := aes.Used(false)
for _, f := range layer.Data.FieldNames() {
found := false
for _, ss := range fields {
if f == ss {
found = true
break
}
}
if found {
continue
}
delete(layer.Data.Columns, f)
}
// Rename mapped fields to their aestethic name
for a, f := range aes {
layer.Data.Rename(f, a)
}
// Step 2b
layer.Panel.Plot.PrepareScales(layer.Data, aes)
for a := range aes {
scale, ok := panel.Scales[a]
if !ok {
continue
}
scale.Train(layer.Data.Columns[a])
}
}
}
// PrepareScales makes sure plot contains all scales needed for the
// aesthetics in aes, the data is scale transformed if requested by the
// scale and the scales are pre-trained.
//
// Only continuous, non-time-scales can be transformed.
//
// Step 2b
func (plot *Plot) PrepareScales(data *DataFrame, aes AesMapping) {
scaleable := map[string]bool{
"x": true,
"y": true,
"color": true,
"fill": true,
"alpha": true,
"size": true,
"linetype": true,
"shape": true,
}
for a := range aes {
if !scaleable[a] {
fmt.Printf(" PrepareScales() %q is un-scalable\n", a)
continue
}
plotScale, plotOk := plot.Scales[a]
panelOk := false
if len(plot.Panels) > 0 {
_, panelOk = plot.Panels[0][0].Scales[a]
}
switch {
case plotOk && panelOk:
// Scale exists and has been distributet to the panels
// already.
fmt.Printf(" PrepareScales() %q already distributed\n", a)
case plotOk && !panelOk:
// Must be a user set scale on plot; just distribute.
fmt.Printf(" PrepareScales() %q distributed from plot\n", a)
plot.distributeScale(plotScale, a)
case !plotOk && !panelOk:
// Auto-generated scale, first occurence of this scale.
name, typ := aes[a], data.Columns[a].Type
fmt.Printf(" PrepareScales() %q create new and distribute\n", a)
plotScale = NewScale(a, name, typ)
plot.Scales[a] = plotScale
plot.distributeScale(plotScale, a)
case !plotOk && panelOk:
panic("This should never happen.")
}
// Transform data if scale request such a transform.
if plotScale.Transform != nil && plotScale.Transform != &IdentityScale {
// TODO: This test should happen much earlier.
if plotScale.Discrete || plotScale.Time {
plot.Warnf("Cannot transform discrete or time scale %s %q",
plotScale.Aesthetic, plotScale.Name)
plotScale.Transform = &IdentityScale
} else {
field := data.Columns[a]
field.Apply(plotScale.Transform.Trans)
fmt.Printf(" Transformed data on scale %v", a)
}
}
/***********************
// Pre-train scales on all panels
// TODO: This is wrong, or? Training is per panel!
for r := range plot.Panels {
for c := range plot.Panels[r] {
scale := plot.Panels[r][c].Scales[a]
scale.Train(data.Columns[a])
fmt.Printf("After training Scale %s on panel %s: [ %.2f, %.2f ]\n", a, plot.Panels[r][c].Name, scale.DomainMin, scale.DomainMax)
}
}
***********************/
}
}
// distributeScale will distribute scale to all panels. Most of the time
// all panels share one instance of a scale. But x- and y-scales may be free
// between rows and columns in which the panels recieve a copy.
func (plot *Plot) distributeScale(scale *Scale, aes string) {
sharing := plot.scaleSharing(aes)
switch sharing {
case "all-panels":
// All panels share the same scale.
for r := range plot.Panels {
for c := range plot.Panels[r] {
plot.Panels[r][c].Scales[aes] = scale
}
}
case "row-shared":
// Each column share an individual copy of the scale.
for r := range plot.Panels {
cpy := *scale
for c := range plot.Panels[r] {
plot.Panels[r][c].Scales[aes] = &cpy
}
}
case "col-shared":
// Add appropriate scale to all panels.
for c := range plot.Panels[0] {
cpy := *scale
for r := range plot.Panels {
plot.Panels[r][c].Scales[aes] = &cpy
}
}
default:
panic("Ooops " + plot.scaleSharing(aes))
}
}
// scaleSharing determines which panels share the sclae for the aesthetic aes:
// Only x and y can be not-shared in a feceted plot with set FreeScale.
func (plot *Plot) scaleSharing(aes string) string {
if aes != "x" && aes != "y" {
return "all-panels"
}
free := plot.Faceting.FreeScale
if free == "" {
return "all-panels"
}
if aes == "x" && strings.Index(free, "x") != -1 {
// Scale for x axis, but x is 'free' i.e. each column may have
// its own x-scale, but this one is shared along the whole
// column.
return "col-shared"
}
if aes == "y" && strings.Index(free, "y") != -1 {
return "row-shared"
}
return "all-panels"
}
// -------------------------------------------------------------------------
// Step 3: Satistical Transformation
func (p *Panel) ComputeStatistics() {
fmt.Printf("Panel %q: ComputeStatistics()\n", p.Name)
for _, layer := range p.Layers {
layer.ComputeStatistics()
}
}
// ComputeStatistics computes the statistical transform. Might be the identity.
//
// Step 3 in design.
func (layer *Layer) ComputeStatistics() {
if layer.Stat == nil {
fmt.Printf(" Layer %q: ComputeStatistics() nil stat\n", layer.Name)
return // The identity statistical transformation.
}
// Make sure all needed aesthetics (columns) are present in
// our data frame.
// Step 3a.
needed := layer.Stat.Info().NeededAes
for _, aes := range needed {
if _, ok := layer.Data.Columns[aes]; !ok {
layer.Panel.Plot.Warnf("Stat %s in Layer %s needs column %s",
layer.Stat.Name(), layer.Name, aes)
// TODO: more cleanup?
layer.Geom = nil // Don't draw anything.
return
}
}
// Handling of excess fields. TODO: Massive refactoring needed.
usedByStat := NewStringSetFrom(needed)
usedByStat.Join(NewStringSetFrom(layer.Stat.Info().OptionalAes))
additionalFields := NewStringSetFrom(layer.Data.FieldNames())
additionalFields.Remove(usedByStat)
// TODO: all handling related code
/***********************************************************
// Make sure all excess fields are discrete and abort on
// any continuous field.
for _, f := range fields.Elements() {
if !layer.Data.Columns[f].Discrete() {
layer.Plot.Warnf("Stat %s in Layer %s cannot cope with continous excess fields %s",
layer.Stat.Name(), layer.Name, f)
// TODO: more cleanup?
layer.Geom = nil // Don't draw anything.
return
}
}
*************************************************************/
before := fmt.Sprintf("%s %d %v", layer.Stat.Name(), layer.Data.N, layer.Data.FieldNames())
handling := layer.Stat.Info().ExtraFieldHandling
switch handling {
case FailOnExtraFields:
if len(additionalFields) > 0 {
layer.Panel.Plot.Warnf(
"Cannot apply stat %s to %s on layer %s: additional fields %v present",
layer.Stat.Name(), layer.Data.Name, layer.Name, additionalFields)
}
layer.Data = nil
case IgnoreExtraFields:
// Do simple transform. Step 3.
layer.Data = layer.Stat.Apply(layer.Data, layer.Panel)
case GroupOnExtraFields:
// Do the transform recursively. Step 3b
layer.Data = applyRec(layer.Data, layer.Stat, layer.Panel, additionalFields.Elements())
}
if layer.Data != nil {
fmt.Printf(" Layer %q: ComputeStatistics() %s --> %d %v\n",
layer.Name, before, layer.Data.N, layer.Data.FieldNames())
} else {
fmt.Printf(" Layer %q: ComputeStatistics() %s --> nil\n",
layer.Name, before)
}
}
// Recursively partition data on the the additional fields, apply stat and
// combine the result.
func applyRec(data *DataFrame, stat Stat, p *Panel, additionalFields []string) *DataFrame {
if len(additionalFields) == 0 {
return stat.Apply(data, p)
}
field := additionalFields[0]
var result *DataFrame
levels := Levels(data, field).Elements()
partition := Partition(data, field, levels)
for i, part := range partition {
// Recursion
part = applyRec(part, stat, p, additionalFields[1:])
// Re-add the field which was stripped during partitioning.
af := data.Columns[field].Const(levels[i], part.N)
part.Columns[field] = af
// Combine results.
if i == 0 {
result = part
} else {
result.Append(part)
}
}
return result
}
// -------------------------------------------------------------------------
// Step 4: Wiring Result of Stat to Input of Geom
func (p *Panel) WireStatToGeom() {
fmt.Printf("Panel %q: WireStatToGeoms()\n", p.Name)
// A stat may return a nil data frame, e.g. if the input to the stat
// itself was empty. In this case no wireing is needed and the layer
// geom can be removed.
for _, layer := range p.Layers {
if layer.Data == nil {
// Data was cleared by stat.
layer.Geom = nil
continue
}
layer.WireStatToGeom()
}
}
func (layer *Layer) WireStatToGeom() {
// Now we have a new data frame with possible new columns.
// These may be mapped to plot aestetics by plot.StatMapping.
// Do this now.
if len(layer.StatMapping) != 0 {
fmt.Printf(" Layer %q: Preparing scales with stat mapping %v\n",
layer.Name, layer.StatMapping)
// Rename mapped fields to their aestethic name
for a, f := range layer.StatMapping {
fmt.Printf(" Layer %q: Renaming %q to %q because of stat mapping.\n",
layer.Name, f, a)
layer.Data.Rename(f, a)
}
layer.Panel.Plot.PrepareScales(layer.Data, layer.StatMapping)
for a := range layer.StatMapping {
scale, ok := layer.Panel.Scales[a]
if !ok {
continue
}
//fmt.Printf("WireStat: Before training Scale %s on panel %s layer %s: [ %.2f, %.2f ]\n",
// a, layer.Panel.Name, layer.Name, scale.DomainMin, scale.DomainMax)
scale.Train(layer.Data.Columns[a])
// fmt.Printf("WireStat: After training Scale %s on panel %s layer %s: [ %.2f, %.2f ]\n",
// a, layer.Panel.Name, layer.Name, scale.DomainMin, scale.DomainMax)
}
}
// TODO: Geoms should contain aesthetict only as input, so there
// should not be a need for both, StatMapping and GeomMapping, or?
// Rename fields produces by statistical transform to names
// the geom understands.
// TODO: When to set e.g. color to a certain value?
for aes, field := range layer.GeomMapping {
layer.Data.Rename(field, aes)
}
}
// -------------------------------------------------------------------------
// Step 5: Constructing Geoms
// ConstructGeoms sets up the geoms so that they can be rendered. This includes
// an optional renaming of stat-generated fields to geom-understandable fields,
// applying positional adjustment to same-x geoms and reparametrization to
// fundamental geoms.
//
func (p *Panel) ConstructGeoms() {
fmt.Printf("Panel %q: ConstructGeoms()\n", p.Name)
for _, layer := range p.Layers {
layer.ConstructGeoms()
}
}
func (layer *Layer) ConstructGeoms() {
if layer.Geom == nil {
if layer.Data != nil {
layer.Panel.Plot.Warnf("No Geom specified in layer %s.", layer.Name)
}
return
}
// Make sure all needed slots are present in the data frame
slots := NewStringSetFrom(layer.Geom.NeededSlots())
dfSlots := NewStringSetFrom(layer.Data.FieldNames())
slots.Remove(dfSlots)
if len(slots) > 0 {
layer.Panel.Plot.Warnf("Missing slots in geom %s in layer %s: %v",
layer.Geom.Name(), layer.Name, slots.Elements())
layer.Geom = nil
return
}
fmt.Printf(" Layer %q geom %q construction from %d data\n",
layer.Name, layer.Geom.Name(), layer.Data.N)
layer.Fundamentals = layer.Geom.Construct(layer.Data, layer.Panel)
}
// -------------------------------------------------------------------------
// Step 6: Prepare Scales
func (p *Panel) FinalizeScales() {
fmt.Printf("Panel %q: FinalizeScales()\n", p.Name)
for _, scale := range p.Scales {
scale.Finalize(p.Plot.Pool)
}
}
// -------------------------------------------------------------------------
// Step 7: Render fundamental Geoms
func (p *Panel) RenderGeoms() {
fmt.Printf("Panel %q: RenderGeoms()\n", p.Name)
for _, layer := range p.Layers {
if len(layer.Fundamentals) == 0 {
continue
}
for _, fund := range layer.Fundamentals {
data := fund.Data
aes := fund.Geom.Aes(p.Plot)
grobs := fund.Geom.Render(p, data, aes)
layer.Grobs = append(layer.Grobs, grobs...)
}
}
}
// -------------------------------------------------------------------------
// Step 8: Render remaining parts of plot
func (plot *Plot) RenderVisuals() {
// Title, X-Label and Y-Label.
if plot.Title != "" {
style := MergeStyles(plot.Theme.Title, DefaultTheme.Title)
size := String2Float(style["size"], 0, 100)
g := GrobText{x: 0.5, y: 0.5, vjust: 0.5, hjust: 0.5,
text: plot.Title, size: size}
plot.Grobs["Title"] = g
_, h := g.BoundingBox()
plot.renderInfo["Title.Height"] = h
}
if name := plot.Scales["x"].Name; name != "" {
style := MergeStyles(plot.Theme.Label, DefaultTheme.Label)
size := String2Float(style["size"], 0, 100)
g := GrobText{x: 0.5, y: 0.5, vjust: 0.5, hjust: 0.5,
text: name, size: size}
plot.Grobs["X-Label"] = g
_, h := g.BoundingBox()
plot.renderInfo["X-Label.Height"] = h
}
if name := plot.Scales["y"].Name; name != "" {
style := MergeStyles(plot.Theme.Label, DefaultTheme.Label)
size := String2Float(style["size"], 0, 100)
g := GrobText{x: 0.5, y: 0.5, vjust: 0.5, hjust: 0.5, text: name,
angle: math.Pi / 2, size: size}
w, _ := g.BoundingBox()
plot.renderInfo["Y-Label.Width"] = w
plot.Grobs["Y-Label"] = g
}
// Strips for facetted plots.
strip := MergeStyles(plot.Theme.Strip, DefaultTheme.Strip)
stripBG := String2Color(strip["fill"])
stripCol := String2Color(strip["color"])
stripSize := String2Float(strip["size"], 4, 100)
if len(plot.Faceting.RowStrips) > 0 {
ncols := len(plot.Panels[0])
maxWidth := vg.Length(0)
for r := range plot.Panels {
strip := plot.Faceting.RowStrips[r]
// TDOO: Add border.
rect := GrobRect{xmin: 0, ymin: 0, xmax: 1, ymax: 1, fill: stripBG}
text := GrobText{x: 0.5, y: 0.5, vjust: 0.5, hjust: 0.5,
text: strip, angle: math.Pi / 2,
size: stripSize, color: stripCol}
plot.Panels[r][ncols-1].Rgr = []Grob{rect, text}
w, _ := text.BoundingBox()
if w > maxWidth {
maxWidth = w
}
fmt.Printf("Strip %q %.1f %.1f\n", strip, w, maxWidth)
}
plot.renderInfo["Row-Strip.Width"] = maxWidth
}
if len(plot.Faceting.ColStrips) > 0 {
nrows := len(plot.Panels)
maxHeight := vg.Length(0)
for c := range plot.Panels[0] {
strip := plot.Faceting.ColStrips[c]
// TDOO: Add border.
rect := GrobRect{xmin: 0, ymin: 0, xmax: 1, ymax: 1, fill: stripBG}
text := GrobText{x: 0.5, y: 0.5, vjust: 0.5, hjust: 0.5,
text: strip, angle: 0,
size: stripSize, color: stripCol}
plot.Panels[nrows-1][c].Tgr = []Grob{rect, text}
_, h := text.BoundingBox()
if h > maxHeight {
maxHeight = h
}
}
plot.renderInfo["Col-Strip.Height"] = maxHeight
}
plot.RenderGuides()
}
func (plot *Plot) RenderGuides() {
maxWidth := vg.Length(0)
yCum := vg.Length(0)
ySep := vg.Length(5) // TODO; make configurable
guides := GrobGroup{x0: 0, y0: 0}
for aes, scale := range plot.Scales {
if aes == "x" || aes == "y" {
// X and y axes are draw on a per-panel base.
continue
}
fmt.Printf("%s\n", scale.String())
grobs, width, height := scale.Render()
if width > maxWidth {
maxWidth = width
}
gg := grobs.(GrobGroup)
gg.y0 = float64(yCum)
guides.elements = append(guides.elements, gg)
yCum += height + ySep
}
plot.Grobs["Guides"] = guides
plot.renderInfo["Guides.Width"] = maxWidth
}
// -------------------------------------------------------------------------
// Panel creation
// CreatePanels populates p.Panels, governed by p.Faceting.
//
// Not only p.Data is facetted but p.Layers also (if they contain own data).
func (plot *Plot) CreatePanels() {
if plot.Faceting.Columns == "" && plot.Faceting.Rows == "" {
plot.createSinglePanel()
} else {
plot.createGridPanels()
}
}
func (plot *Plot) createSinglePanel() {
// println("createSinglePanel()")
panel := &Panel{
Plot: plot,
Data: plot.Data,
Aes: plot.Aes.Copy(),
Layers: make([]*Layer, len(plot.Layers)),
Scales: make(map[string]*Scale),
}
plot.Panels = [][]*Panel{[]*Panel{panel}}
for i, layer := range plot.Layers {
plot.Panels[0][0].Layers[i] = layer
plot.Panels[0][0].Layers[i].Panel = panel
}
fmt.Printf("After createSinglePanel plot.Panels = %+v\n", plot.Panels)
}
func (p *Plot) createGridPanels() {
// println("createGridPanel()")
// Process faceting: How many facets are there, how are they named
rows, cols := 1, 1
var cunq []float64
var runq []float64
// Make sure facetting can be done and determine number of
// rows and columns.
if p.Faceting.Columns != "" {
f := p.Data.Columns[p.Faceting.Columns]
if !f.Discrete() {
panic(fmt.Sprintf("Cannot facet over %s (type %s)",
p.Faceting.Columns, f.Type.String()))
}
cunq = Levels(p.Data, p.Faceting.Columns).Elements()
cols = len(cunq)
p.Faceting.ColStrips = make([]string, cols)
for c := 0; c < cols; c++ {
p.Faceting.ColStrips[c] = f.String(cunq[c])
}
}
if p.Faceting.Rows != "" {
f := p.Data.Columns[p.Faceting.Rows]
if !f.Discrete() {
panic(fmt.Sprintf("Cannot facet over %s (type %s)",
p.Faceting.Columns, f.Type.String()))
}
runq = Levels(p.Data, p.Faceting.Rows).Elements()
rows = len(runq)
p.Faceting.RowStrips = make([]string, rows)
for r := 0; r < rows; r++ {
p.Faceting.RowStrips[r] = f.String(runq[r])
}
}
p.Panels = make([][]*Panel, rows, rows+1)
for r := 0; r < rows; r++ {
p.Panels[r] = make([]*Panel, cols, cols+1)
rowData := Filter(p.Data, p.Faceting.Rows, runq[r])
for c := 0; c < cols; c++ {
panel := &Panel{
Name: fmt.Sprintf("%d/%d %s/%s", r, c, p.Faceting.RowStrips[r], p.Faceting.ColStrips[c]),
Plot: p,
Scales: make(map[string]*Scale),
Data: Filter(rowData, p.Faceting.Columns, cunq[c]),
}
for _, orig := range p.Layers {
// Copy plot layers to panel, make sure layer data is filtered.
layer := &Layer{
Panel: panel,
Name: orig.Name,
Stat: orig.Stat,
Geom: orig.Geom,
DataMapping: orig.DataMapping,
StatMapping: orig.StatMapping,
GeomMapping: orig.GeomMapping,
}
if orig.Data != nil {
layer.Data = Filter(orig.Data, p.Faceting.Rows, runq[r])
layer.Data = Filter(layer.Data, p.Faceting.Columns, cunq[c])
}
panel.Layers = append(panel.Layers, layer)
}
p.Panels[r][c] = panel
if p.Faceting.Totals {
// Add a total columns containing all data of this row.
panel := &Panel{
Name: fmt.Sprintf("%d/%d %s/-all-",
r, c+1, p.Faceting.RowStrips[r]),
Plot: p,
Data: rowData,
Scales: make(map[string]*Scale),
}
for _, layer := range p.Layers {
if layer.Data != nil {
layer.Data = Filter(layer.Data, p.Faceting.Rows, runq[r])
}
layer.Panel = panel
panel.Layers = append(panel.Layers, layer)
}
p.Panels[r] = append(p.Panels[r], panel)
}
}
}
if p.Faceting.Totals {
// Add a total row containing all column data.