ggplot-rs 0.35.3

A Rust implementation of ggplot2's Grammar of Graphics
Documentation
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
# ggplot-rs

[![CI](https://github.com/sipemu/ggplot-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/sipemu/ggplot-rs/actions/workflows/ci.yml)
[![Crates.io](https://img.shields.io/crates/v/ggplot-rs.svg)](https://crates.io/crates/ggplot-rs)
[![npm](https://img.shields.io/npm/v/@sipemu/ggplot-rs.svg)](https://www.npmjs.com/package/@sipemu/ggplot-rs)
[![Documentation](https://docs.rs/ggplot-rs/badge.svg)](https://docs.rs/ggplot-rs)
[![codecov](https://codecov.io/gh/sipemu/ggplot-rs/branch/main/graph/badge.svg)](https://codecov.io/gh/sipemu/ggplot-rs)
[![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](#license)

A Rust implementation of ggplot2's Grammar of Graphics, rendering through a
self-contained SVG backend (no dependencies) or, with the default `plotters`
feature, the [plotters](https://github.com/plotters-rs/plotters) SVG/bitmap backend.

**Validated against R.** Computed layers — binning, density, stacking, QQ/ECDF,
LOESS, and axis-tick placement (extended-Wilkinson) — are checked against
[R ggplot2](https://ggplot2.tidyverse.org/) 4.0.3's `ggplot_build()` output, so a
histogram or a stacked bar comes out where ggplot2 puts it. See
[`validation/`](validation/).

**No polars required.** [polars](https://pola.rs/) is a convenient — and fully
optional — input adapter. The core pipeline runs on its own internal DataFrame,
so you can plot straight from plain Rust vectors, or from
[Apache Arrow](https://arrow.apache.org/) `RecordBatch`es produced by
[DuckDB](https://duckdb.org/) — with polars switched off entirely. See
[Data Input](#data-input) and [Feature Flags](#feature-flags).

## Gallery

Every image below is produced by [`examples/gallery.rs`](examples/gallery.rs) —
regenerate them all with `cargo run --features sf --example gallery` (the
choropleth needs the `sf` feature; drop it for the rest). The
`supplier_leadtime*.png` images come from
[`examples/supplier_leadtime.rs`](examples/supplier_leadtime.rs), and
`inventory_twin.png` from [`examples/inventory_twin.rs`](examples/inventory_twin.rs)
(its composed SVG, rasterised), and `map_tiles.png` from
[`examples/map_tiles.rs`](examples/map_tiles.rs) (`--features tiles,plotters`).

<table>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/scatter.png" width="260" alt="Grouped scatter"><br>
      <sub>Grouped scatter · <code>geom_point</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/smooth.png" width="260" alt="LOESS smoothing"><br>
      <sub>LOESS trend + CI · <code>geom_smooth</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/continuous_color.png" width="260" alt="Continuous color"><br>
      <sub>Continuous color · viridis</sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/histogram.png" width="260" alt="Histogram"><br>
      <sub>Histogram · <code>geom_histogram</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/density.png" width="260" alt="Density by group"><br>
      <sub>Densities · <code>geom_density</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/bar.png" width="260" alt="Bar chart"><br>
      <sub>Bar chart · <code>geom_bar</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/boxplot.png" width="260" alt="Boxplot"><br>
      <sub>Boxplots · <code>geom_boxplot</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/violin.png" width="260" alt="Violin"><br>
      <sub>Violins · <code>geom_violin</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/jitter.png" width="260" alt="Jitter"><br>
      <sub>Jittered points · <code>geom_jitter</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/contour_filled.png" width="260" alt="Filled contours"><br>
      <sub>Filled contours · <code>geom_contour_filled</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/hexbin.png" width="260" alt="Hex binning"><br>
      <sub>Hex binning · <code>geom_hex</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/heatmap.png" width="260" alt="Heatmap"><br>
      <sub>Heatmap · <code>geom_tile</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/flows.png" width="260" alt="Flows between cities"><br>
      <sub>Directed flows · <code>geom_curve</code> + <code>arrow()</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/ribbon.png" width="260" alt="Ribbon"><br>
      <sub>Confidence band · <code>geom_ribbon</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/area.png" width="260" alt="Stacked area"><br>
      <sub>Stacked area · <code>geom_area</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/facet.png" width="260" alt="Facet wrap"><br>
      <sub>Small multiples · <code>facet_wrap</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/polar.png" width="260" alt="Polar rose chart"><br>
      <sub>Rose chart · <code>coord_polar</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/ecdf.png" width="260" alt="Empirical CDF"><br>
      <sub>Empirical CDF · <code>stat_ecdf</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/qq.png" width="260" alt="Q-Q plot"><br>
      <sub>Q-Q plot · <code>geom_qq</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/spatial.png" width="260" alt="Choropleth"><br>
      <sub>Choropleth · <code>geom_sf</code> <sub>(feature <code>sf</code>)</sub></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/legend_wrap.png" width="260" alt="Auto-wrapped legend"><br>
      <sub>Auto-wrapped legend · <code>guide_legend</code> (0.22)</sub>
    </td>
    <td align="center">
      <img src="assets/gallery/boxplot_identity.png" width="260" alt="Boxplot stat identity"><br>
      <sub>Five-number summary · <code>stat = "identity"</code> (0.22)</sub>
    </td>
  </tr>
</table>

### More chart types

Highcharts-style chart types, each one layer in the grammar (tracked under the
[`highcharts-parity`](https://github.com/sipemu/ggplot-rs/labels/highcharts-parity) label).

<table>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/candlestick.png" width="260" alt="Candlestick"><br>
      <sub>Candlestick · <code>geom_candlestick</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/heikin_ashi.png" width="260" alt="Heikin-Ashi"><br>
      <sub>Heikin-Ashi · <code>geom_heikin_ashi</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/renko.png" width="260" alt="Renko bricks"><br>
      <sub>Renko bricks · <code>geom_renko</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/indicators.png" width="260" alt="SMA + Bollinger bands"><br>
      <sub>SMA + Bollinger bands · <code>StatIndicator</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/flags.png" width="260" alt="Event flags"><br>
      <sub>Event flags · <code>geom_flags</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/waterfall.png" width="260" alt="Waterfall / bridge"><br>
      <sub>Waterfall / bridge · <code>geom_waterfall</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/pareto.png" width="260" alt="Pareto"><br>
      <sub>Pareto · <code>geom_pareto</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/bullet.png" width="260" alt="Bullet chart"><br>
      <sub>Bullet chart · <code>geom_bullet</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/funnel.png" width="260" alt="Funnel"><br>
      <sub>Funnel · <code>geom_funnel</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/marimekko.png" width="260" alt="Marimekko"><br>
      <sub>Marimekko · <code>geom_marimekko</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/dumbbell.png" width="260" alt="Dumbbell"><br>
      <sub>Dumbbell · <code>geom_dumbbell</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/spline.png" width="260" alt="Spline line + band"><br>
      <sub>Spline line + band · <code>Interpolate::MonotoneCubic</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/stream.png" width="260" alt="Streamgraph"><br>
      <sub>Streamgraph · <code>geom_stream</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/gantt.png" width="260" alt="Gantt / X-range"><br>
      <sub>Gantt / X-range · <code>geom_xrange</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/timeline.png" width="260" alt="Timeline"><br>
      <sub>Timeline · <code>geom_timeline</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/sankey.png" width="260" alt="Sankey"><br>
      <sub>Sankey · <code>geom_sankey</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/chord.png" width="260" alt="Chord diagram"><br>
      <sub>Chord diagram · <code>geom_chord</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/arcdiagram.png" width="260" alt="Arc diagram"><br>
      <sub>Arc diagram · <code>geom_arcdiagram</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/network.png" width="260" alt="Network graph"><br>
      <sub>Network graph · <code>geom_network</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/org_chart.png" width="260" alt="Org chart"><br>
      <sub>Org chart · <code>geom_tree_with</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/dendrogram.png" width="260" alt="Dendrogram"><br>
      <sub>Dendrogram · <code>geom_dendrogram</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/treemap.png" width="260" alt="Treemap"><br>
      <sub>Treemap · <code>geom_treemap</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/sunburst.png" width="260" alt="Sunburst"><br>
      <sub>Sunburst · <code>geom_sunburst</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/packed_bubble.png" width="260" alt="Packed bubbles"><br>
      <sub>Packed bubbles · <code>geom_packed_bubble</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/venn.png" width="260" alt="Venn / Euler"><br>
      <sub>Venn / Euler · <code>geom_venn</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/waffle.png" width="260" alt="Waffle"><br>
      <sub>Waffle · <code>geom_waffle</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/parliament.png" width="260" alt="Parliament"><br>
      <sub>Parliament · <code>geom_parliament</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/wordcloud.png" width="260" alt="Word cloud"><br>
      <sub>Word cloud · <code>geom_wordcloud</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/variable_pie.png" width="260" alt="Variable-radius pie"><br>
      <sub>Variable-radius pie · <code>geom_variable_pie</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/tilemap.png" width="260" alt="Hex tile map"><br>
      <sub>Hex tile map · <code>geom_tilemap</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/windbarb.png" width="260" alt="Wind barbs"><br>
      <sub>Wind barbs · <code>geom_windbarb</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/radar.png" width="260" alt="Radar"><br>
      <sub>Radar · <code>coord_radar</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/gauge.png" width="260" alt="Gauge"><br>
      <sub>Gauge · <code>CoordPolar::with_span</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/calendar.png" width="260" alt="Calendar heatmap"><br>
      <sub>Calendar heatmap · <code>geom_calendar</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/flow_map.png" width="260" alt="Flow map"><br>
      <sub>Flow map · <code>geom_flow</code> (<code>sf</code>)</sub>
    </td>
  </tr>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/inventory_twin.png" width="260" alt="Inventory twin"><br>
      <sub>Inventory twin · quantile fan + <code>PlotGrid</code> alarm strip</sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/map_tiles.png" width="260" alt="Map tiles"><br>
      <sub>Tiled basemap · <code>annotation_map_tile</code> (<code>tiles</code>)</sub>
    </td>
  </tr>
</table>

| Family | Builders |
|---|---|
| Business / KPI | `geom_waterfall`, `geom_pareto`, `geom_bullet`, `geom_funnel`, `geom_pyramid`, `geom_variwide`, `geom_marimekko`, `geom_lollipop`, `geom_dumbbell` |
| Time | `geom_stream` (stack offsets), `Interpolate` splines on line/area/ribbon, `geom_timeline`, `geom_xrange` (Gantt), `geom_flags` |
| Flows & networks | `geom_sankey`, `geom_chord`, `geom_arcdiagram`, `geom_network`, `geom_flow` (`sf`) |
| Hierarchies | `geom_treemap`, `geom_sunburst`, `geom_icicle`, `geom_tree` / org charts, `geom_dendrogram`, `geom_packed_bubble` |
| Sets & units | `geom_venn`, `geom_waffle`, `geom_parliament`, `geom_wordcloud`, `geom_variable_pie` |
| Finance | `geom_candlestick` (filled / hollow), `geom_ohlc`, `geom_hlc`, `geom_heikin_ashi`, `geom_renko`, `geom_point_figure`, `StatIndicator` (SMA, EMA, WMA, Bollinger, MACD, RSI, ATR, VWAP, stochastic, ZigZag) |
| Maps & weather | `geom_sf`, `coord_sf`, `geom_tilemap` (+ `us_state_grid`), `geom_flow` (`sf`), `annotation_map_tile` (`tiles`), `geom_windbarb` |
| Radial | `coord_polar`, `coord_radar`, gauges via `CoordPolar::with_span` |

### Publication-ready (ggpubr-style)

Journal palettes, `theme_pubr()`, GAM smoothing, and statistical annotations —
the last two need the `regression` / `ggpubr` features. Regenerate with
`cargo run --no-default-features --features regression,ggpubr,plotters --example ggpubr_gallery`.

<table>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/palettes_ggsci.png" width="260" alt="ggsci palette"><br>
      <sub>Journal palettes · <code>scale_color_brewer(Npg)</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/theme_pubr.png" width="260" alt="theme_pubr"><br>
      <sub>Publication theme · <code>theme_pubr</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/smooth_gam.png" width="260" alt="GAM smoothing"><br>
      <sub>GAM smoother · <code>geom_smooth</code> gam <sub>(feature <code>regression</code>)</sub></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/stat_cor.png" width="260" alt="stat_cor"><br>
      <sub>Correlation label · <code>stat_cor</code> <sub>(feature <code>ggpubr</code>)</sub></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/compare_means.png" width="260" alt="stat_compare_means"><br>
      <sub>Group p-value · <code>stat_compare_means</code> <sub>(feature <code>ggpubr</code>)</sub></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/brackets.png" width="260" alt="pairwise brackets"><br>
      <sub>Pairwise brackets · <code>stat_compare_means(comparisons)</code> / <code>geom_bracket</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center" colspan="3">
      <img src="assets/gallery/arrange.png" width="540" alt="ggarrange"><br>
      <sub>Multi-plot composition · <code>ggarrange</code> + one-call constructors (<code>ggscatter</code>/<code>ggboxplot</code>/<code>ggdensity</code>)</sub>
    </td>
  </tr>
</table>

### Themes

The same plot under each built-in theme — swap with a single `.theme(theme_*())` call.

<table>
  <tr>
    <td align="center" width="33%">
      <img src="assets/gallery/theme_gray.png" width="240" alt="theme_gray"><br>
      <sub><code>theme_gray</code> (default)</sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/theme_bw.png" width="240" alt="theme_bw"><br>
      <sub><code>theme_bw</code></sub>
    </td>
    <td align="center" width="33%">
      <img src="assets/gallery/theme_minimal.png" width="240" alt="theme_minimal"><br>
      <sub><code>theme_minimal</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/theme_classic.png" width="240" alt="theme_classic"><br>
      <sub><code>theme_classic</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/theme_light.png" width="240" alt="theme_light"><br>
      <sub><code>theme_light</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/theme_dark.png" width="240" alt="theme_dark"><br>
      <sub><code>theme_dark</code></sub>
    </td>
  </tr>
  <tr>
    <td align="center">
      <img src="assets/gallery/theme_linedraw.png" width="240" alt="theme_linedraw"><br>
      <sub><code>theme_linedraw</code></sub>
    </td>
    <td align="center">
      <img src="assets/gallery/theme_void.png" width="240" alt="theme_void"><br>
      <sub><code>theme_void</code></sub>
    </td>
    <td align="center"></td>
  </tr>
</table>

## Quick Start

```rust
use ggplot_rs::prelude::*;
use polars::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let df = df! {
        "sepal_length" => [5.1, 4.9, 4.7, 7.0, 6.4],
        "sepal_width"  => [3.5, 3.0, 3.2, 3.2, 3.2],
        "species"      => ["setosa", "setosa", "setosa", "versicolor", "versicolor"],
    }?;

    GGPlot::new(df)
        .aes(Aes::new().x("sepal_length").y("sepal_width").color("species"))
        .geom_point()
        .save("scatter.svg")?;

    Ok(())
}
```

## Features

### Geoms

`geom_point`, `geom_line`, `geom_bar`, `geom_col`, `geom_histogram`, `geom_boxplot`, `geom_violin`, `geom_smooth`, `geom_density`, `geom_area`, `geom_ribbon`, `geom_errorbar`, `geom_segment`, `geom_rug`, `geom_text`, `geom_label`, `geom_tile`, `geom_raster`, `geom_bin2d`, `geom_hex`, `geom_contour`, `geom_contour_filled`, `geom_path`, `geom_step`, `geom_hline`, `geom_vline`, `geom_abline`, and more (40+)

- **`geom_boxplot(stat = "identity")`** (0.22): supply the five-number summary directly via `Aes::lower`/`middle`/`upper` (plus the usual `ymin`/`ymax`) instead of letting ggplot-rs compute it, with an `Aes::outliers("7, 9")` comma list (brackets optional) drawn as points that now also widen the y axis to fit them. The box reads `tooltip()`/`data_attr()` like any other geom.
- **`geom_text`/`geom_label` honour a discrete `position_dodge`** (0.22), landing at the same x as a dodged `geom_col`'s bar centres.
- **`geom_errorbar` caps shrink under a discrete `position_dodge`** (0.22) by the number of dodged groups, so adjacent caps don't visually overlap.

### Stats

`StatIdentity`, `StatCount`, `StatBin`, `StatBoxplot`, `StatSmooth` (Lm + Loess), `StatDensity`, `StatLoess`, `StatSummary`, `StatEcdf`, `StatFunction`, `StatEllipse`, `StatContour`, `StatBin2d`, `StatBinHex`, `StatSum`, `StatYDensity`, `StatQQ`, `StatSummary2d`, `StatQuantile` (feature `regression`), and more

### Scales

- **Continuous**: linear, log10, log2, ln, sqrt, reverse, logit, probit, pseudo-log, reciprocal, exp, and Box–Cox transforms
- **Discrete**: automatic categorical mapping
- **Color**: discrete palettes (Viridis, Brewer Set1/Dark2, etc.), continuous gradients, diverging gradient2, binned/stepped scales (`scale_color_steps`/`fermenter`), manual color assignment
- **Shape & Linetype**: discrete mapping for point shapes and line styles
- **`scale_size_area(max_size)`** (0.22): size scale where *area* — not radius — is proportional to the value, so 0 maps to 0 (ggplot2 parity).
- **Locale-aware labels**: `GGPlot::locale(Locale::from_tag("de-DE"))` renders default axis and legend labels with the locale's marks (`1.000`, `2,5`) and date axes with its month names (`Okt. 2026`, `15. Okt. 2026`); presets `en_us`, `en_gb`, `de_de`, `fr_fr`. Without it, output is unchanged.

```rust
use ggplot_rs::prelude::*;

let de = Locale::from_tag("de-DE");
assert_eq!(label_currency_locale(&de, Some(0.01))(1234.5), "1.234,50 €");
assert_eq!(label_currency_locale(&Locale::en_us(), Some(0.01))(1234.5), "$1,234.50");
assert_eq!(label_percent_locale(&de, None)(0.123), "12,3 %");
assert_eq!(label_number_marks(Some(0.1), "", " kg", 1.0, ",", ".")(1234.56), "1.234,6 kg");

// Plot-wide: German number marks on every default axis/legend, German month names.
let plot = GGPlot::new(df)
    .aes(Aes::new().x("date").y("revenue"))
    .geom_line()
    .scale_y_continuous(ScaleContinuous::new().with_label_formatter(label_currency_locale(&de, None)))
    .locale(de);
```

### Coordinates

`coord_cartesian`, `coord_flip`, `coord_fixed`, `coord_polar`, `coord_trans`

### Spatial (`geom_sf`)

Behind the optional `sf` feature, `geom_sf` renders simple-features geometry —
points, lines, and (multi)polygons with holes — from a `geometry` column of
**WKT** strings. It uses a self-contained WKT parser, so the spatial layer pulls
in **no** extra dependencies. The `fill` aesthetic drives a choropleth, and
axes/legends/facets come from the rest of the grammar as usual:

```rust
let df = df! {
    "geometry"   => ["POLYGON ((0 0, 3 0, 3 2, 0 2, 0 0))", "POLYGON ((3 0, 6 0, 6 3, 3 2, 3 0))"],
    "population" => [4.2, 9.5],
}?;
GGPlot::new(df)
    .aes(Aes::new().fill("population"))
    .geom_sf()
    .scale_fill_viridis_c();
```

**Projections & aspect.** Pass a projection to `geom_sf` and pair it with
`coord_sf()` (equal-aspect, derived from the data extent) for a shape-correct
map — e.g. a conformal Web Mercator:

```rust
use ggplot_rs::spatial::SfProjection;
use ggplot_rs::geom::sf::GeomSf;

GGPlot::new(df)                        // lon/lat WKT in `geometry`
    .aes(Aes::new().fill("value"))
    .geom_sf_with(GeomSf::default().project(SfProjection::Mercator))
    .coord_sf();
```

**Load GeoJSON.** The `geojson` feature reads a `FeatureCollection` into a
plot-ready frame — geometry → WKT, properties → columns:

```rust
use ggplot_rs::spatial::geojson::read_geojson_file;

let cols = read_geojson_file("countries.geojson")?;   // Vec<(String, Vec<Value>)>
GGPlot::new(cols).aes(Aes::new().fill("gdp")).geom_sf();
```

See [`examples/spatial.rs`](examples/spatial.rs) (`cargo run --features sf --example spatial`).

### Faceting

`facet_wrap` and `facet_grid` with free/fixed scales, proportional panel sizing
(`space = "free"` via `facet_grid_space`), and multi-variable columns
(`facet_grid_multi`, R's `rows ~ b + c`). Computed stats (density/histogram) are
estimated per panel, and so is `position_stack`/`position_fill` (0.22) — a
faceted stacked bar no longer mixes rows from different panels into one
shared total.

### Positions

`position_identity`, `position_dodge`/`dodge2`, `position_jitter`/`jitterdodge`,
`position_nudge`, and `position_stack`/`position_fill` — both take a `vjust`
(0.22, ggplot2's `position_stack(vjust =)`): `1` (default) places a segment's
label at its top, `0.5` at its centre, `0` at its bottom.

### Themes

`theme_gray`, `theme_bw`, `theme_classic`, `theme_minimal`, `theme_dark`, `theme_light`, `theme_linedraw`, `theme_void` — plus full customization via `ElementText`, `ElementLine`, `ElementRect`

### Annotations

`annotate_text`, `annotate_rect`, `annotate_segment`

### Guides & axes

- **Legend inside the panel** at panel-relative coords: `legend_position_inside(x, y)` (R's `legend.position = c(x, y)`).
- **Axis label rotation**: `axis_text_x_angle(deg)` / `axis_text_y_angle(deg)` (R's `guide_axis(angle = ...)`).
- **Label dodging**: `axis_text_x_dodge(n)` staggers crowded x labels across `n` rows (`guide_axis(n.dodge)`).
- **Outer-label fit** (0.22): `axis_text_x_fit(AxisLabelFit::Reserve | Shift | Clip)` keeps an outer x label on-canvas instead of letting it cross the SVG edge — `Reserve` (default) grows the panel margin just enough, `Shift` moves the label at draw time without resizing the panel, `Clip` is the pre-0.22 behaviour.
- **`check.overlap`** (0.22): `axis_text_x_check_overlap(true)` thins crowded x labels in ggplot2's own priority order (first, last, then the busiest middle), off by default.
- **Legend `nrow`/`ncol`/`byrow` and auto-wrap** (0.22): `guides(GuideLegend::new().with_nrow/ncol(n).with_byrow(true))` lays out an explicit grid (column-major, or row-major with `byrow`); with neither set, an overflowing single horizontal legend auto-wraps, ending in "+N more" (`with_max_rows(n)` caps the growth) when it still doesn't fit.
- **Corner tag**: `tag("A")` for figure-panel labels (`labs(tag)`).
- **Axis position & expansion**: `ScaleContinuous::with_position_opposite()` (x-axis on top / y on the right) and `with_expand_sides(...)` for per-side expansion.

Call theme-related builders after any `theme_*()` preset.

### Computed aesthetics

An aesthetic can map an **expression** over columns, not just a bare column name:

```rust
GGPlot::new(data)
    .aes(Aes::new().x("log10(gdp)").y("pop / 1e6").color("deaths / cases"))
    .geom_point();
```

Supports `+ - * / % ^`, parentheses, and `ln`/`log`/`log10`/`log2`/`sqrt`/`exp`/`abs`/`sin`/`cos`/`tan`/`floor`/`ceil`/`round`/`sign`. A plain column name is used directly (so existing mappings are unchanged); anything else is parsed and evaluated per row. `after_scale_fill_from_color(l)` / `after_scale_color_from_fill(l)` derive one color aesthetic from another's mapped color, lightness-adjusted (`after_scale`); `Aes::stage(aes, start, after_stat)` maps an aesthetic at two pipeline stages. The same expressions work in `after_stat` mappings, plus aggregate functions (`sum`, `mean`, `max`, `min`, `count`, `median`, `prod`) that reduce over all rows — e.g. `.after_stat_y("count / sum(count)")` for proportion histograms.

## Command-line tool

A `ggplot-rs` CLI (behind the `cli` feature) plots **parquet**/**CSV** files or
**DuckDB SQL** straight from the shell — DuckDB is the query engine:

```sh
cargo install ggplot-rs --features cli

# discover columns first, then plot
ggplot-rs --parquet sales.parquet --describe
ggplot-rs --parquet sales.parquet --x month --y revenue --geom line -o rev.png

# aggregate with SQL (reads parquet globs), faceted bars
ggplot-rs --sql "SELECT region, sum(qty) q FROM 'orders/*.parquet' GROUP BY 1" \
  --x region --y q --geom col --facet-wrap region --theme minimal -o orders.svg
```

Flags: `--x/--y/--color/--fill/--size/--shape/--group`, `--geom`, `--facet-wrap/--facet-grid`,
`--log-x/--log-y/--flip`, `--title/--subtitle/--xlab/--ylab/--caption`, `-o FILE`/`--stdout`,
`--width/--height`. Run `--describe` to list a source's columns and types.

**Maps from the CLI (`--spatial`, `--geom sf`).** DuckDB's
[`spatial`](https://duckdb.org/docs/extensions/spatial) extension reads
**shapefiles**, GeoJSON, GeoPackage, FlatGeobuf and more (via GDAL). Pass
`--spatial` to load it, then `ST_AsText(geom)` any geometry into a `geometry`
column and plot it with `--geom sf`:

```sh
ggplot-rs --spatial \
  --sql "SELECT ST_AsText(geom) AS geometry, name, pop_est
         FROM ST_Read('ne_110m_admin_0_countries.shp')" \
  --geom sf --fill pop_est --projection mercator --theme void -o world.png
```

`ST_Read` handles the file format; `ST_AsText` produces WKT that `geom_sf`
consumes; `--projection mercator` and an equal-aspect `coord_sf` are applied
automatically. Any SQL works, so you can join, filter, or aggregate spatial and
tabular data in the same query before plotting.

**Theming from the CLI:** `--theme <preset>` (gray/bw/minimal/…), `--palette <name>`
(Set1/Dark2/viridis/RdBu/…), `--primary "r,g,b"` (brand color), and `--theme-config <file>`
— a TOML/JSON file of element overrides for full custom theming:

```sh
ggplot-rs --parquet d.parquet --x a --y b --color g --palette Dark2 --primary "26,153,136" -o p.png
ggplot-rs --parquet d.parquet --x a --y b --color g --theme-config brand.toml -o p.png
```

```toml
# brand.toml — applied on top of the base preset
base = "minimal"
palette = "RdBu"
primary = [200, 60, 40]
[title]
size = 22
color = [40, 40, 90]
[panel_background]
fill = [248, 246, 240]
[panel_grid_major]
linetype = "dashed"
[legend]
position = "inside"
x = 0.9
y = 0.9
```

**AI-ready:** the repo ships a Claude Code skill at `.claude/skills/plot-data/` that
teaches an agent the describe-then-map-then-render workflow, so "plot this parquet"
just works.

## In the browser (WASM)

### npm: `@sipemu/ggplot-rs`

[![npm](https://img.shields.io/npm/v/@sipemu/ggplot-rs.svg)](https://www.npmjs.com/package/@sipemu/ggplot-rs)

The same grammar from JavaScript/TypeScript: a typed, layered spec in, an SVG
string out. It works in the browser (Vite, plain ESM, Observable) and in Node,
with no runtime dependencies. The `.wasm` file is about 0.6 MB gzipped. See
[`js/README.md`](js/README.md) for the quickstart and the full spec.

```sh
npm i @sipemu/ggplot-rs
```

```js
import init, { render } from "@sipemu/ggplot-rs";
await init();
const svg = render({
  data: { x: [1, 2, 3], y: [2, 4, 3], g: ["a", "b", "a"] },
  aes: { x: "x", y: "y", color: "g" },
  layers: [{ geom: "point" }, { geom: "line" }],
  facet: { wrap: "g" },
  labels: { title: "Hello from npm" },
});
```

The npm version always matches the crate version.

### The wasm crate

**▶ Live demo: <https://sipemu.github.io/ggplot-rs/>** — DuckDB-Wasm reads Natural
Earth countries into a hover-able choropleth, plus a **100k-point scatter** via the
raster backend.

The [`crates/ggplot-rs-wasm`](crates/ggplot-rs-wasm) workspace crate (a `cdylib`,
not published) exposes a plotters-free renderer to JavaScript via `wasm-bindgen`.
It compiles to `wasm32` and uses the self-contained [`SvgBackend`](#rendering), so
the bundle needs no polars and no fonts (text is `<text>`, which the browser
draws). The `ggplot-rs` library itself is a plain `rlib` with no
wasm-specific dependencies, so it also builds for `wasm32-unknown-unknown` /
emscripten targets directly (`default-features = false`):

```sh
wasm-pack build crates/ggplot-rs-wasm --target web --out-dir ../../web/pkg --out-name ggplot_rs
```

```js
import init, { render_geo } from "./pkg/ggplot_rs.js";
await init();
document.getElementById("plot").innerHTML = render_geo(JSON.stringify({
  geometry: [...wkt], fill: [...nums], label: [...names], projection: "mercator",
}));
```

Every mark is a real DOM element, so **hover works out of the box** — each feature
carries a `<title>` tooltip (from a `label` mapping + the fill value), plus CSS
`:hover` for highlight.

Pair it with **[DuckDB-Wasm](https://github.com/duckdb/duckdb-wasm)** (which loads
the same `spatial` extension) to read shapefiles/GeoJSON and `ST_AsText` them to
WKT entirely client-side.

**Large N.** SVG is one DOM node per mark (great to ~10k–50k). For more, the
`canvas` feature adds a self-contained **RGBA raster backend** (`render_rgba` /
`render_png_raster`, or the wasm crate's `render_scatter_rgba`) — it rasterises everything in
pure Rust (text via `ab_glyph`), so it's fast and wasm-compatible: 500k points
render in a fraction of a second to a bitmap you blit with `putImageData`. (Or
aggregate in DuckDB — `GROUP BY`, hex-bins, sampling — and render the summary.)
See [`web/`](web/) for a runnable demo that fetches Natural Earth countries:

<p align="center"><img src="assets/gallery/world.png" width="640" alt="World population choropleth from Natural Earth via DuckDB spatial"></p>

The same render is one CLI command (native, identical `render_svg_native` path):

```sh
ggplot-rs --spatial \
  --sql "SELECT ST_AsText(geom) AS geometry, NAME AS label, ln(POP_EST+1) AS pop
         FROM ST_Read('ne_110m_admin_0_countries.geojson') WHERE NAME <> 'Antarctica'" \
  --geom sf --fill pop --label label --theme void -o world.png
```

## Data Input

`GGPlot::new` accepts anything implementing the `GGData` trait. Nothing here
requires polars — pick whichever source fits your stack.

**Plain Rust — zero optional dependencies:**

```rust
// Column-oriented
let cols: Vec<(String, Vec<Value>)> = vec![
    ("x".into(), vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0)]),
    ("y".into(), vec![Value::Float(4.0), Value::Float(5.0), Value::Float(6.0)]),
];
GGPlot::new(cols)

// Row-oriented
let rows: Vec<HashMap<String, Value>> = vec![/* ... */];
GGPlot::new(rows)
```

**Apache Arrow / DuckDB** — feed a `RecordBatch` straight from a DuckDB query
result, with polars switched off:

```toml
# Cargo.toml — no polars in the dependency tree (add "plotters" for render_svg/render_png)
ggplot-rs = { version = "0.16", default-features = false, features = ["arrow"] }
```

```rust
let batch: arrow::record_batch::RecordBatch = /* DuckDB query → Arrow */;
GGPlot::new(batch)
```

**polars** (optional, enabled by default) — for `df!` and polars pipelines:

```rust
let df = df! {
    "x" => [1.0, 2.0, 3.0],
    "y" => [4.0, 5.0, 6.0],
}?;
GGPlot::new(df)
```

## Rendering

**Without plotters** (`default-features = false`) — the self-contained SVG
backend, also used in the browser; zero rendering dependencies:

```rust
let svg: String = plot.render_svg_native_with_size(800, 600)?;
```

The remaining methods need the `plotters` feature (on by default). Save to a file (format inferred from the extension — `svg`, `png`, `jpg`, ...):

```rust
plot.save("out.svg")?;              // 800x600 default
plot.save_with_size("out.png", 1200, 800)?;
plot.ggsave("out.png", 6.0, 4.0, 150.0)?; // width_in, height_in, dpi
```

Or render in memory — no temp files — which is what you want when serving charts
from a web/MCP service:

```rust
let svg: String   = plot.clone().render_svg()?;          // or render_svg_with_size(w, h)
let png: Vec<u8>  = plot.render_png_with_size(400, 300)?; // fully-encoded PNG bytes
```

**Headless / no system fonts.** Rendering uses plotters' `ab_glyph` text backend
with a **bundled font** (DejaVu Sans), not `font-kit`/fontconfig — so text renders
deterministically in a minimal container with no system fonts installed. Nothing
to configure; there is no dependency on the host's font stack.

## Theming & brand color

Everything about a theme is set at **runtime**, so one render process can serve
many tenants' brands without touching chart code.

Inject a **brand/primary color** — it becomes the default for any single-series
geom that has no `color`/`fill` aesthetic mapped (an explicit mapping always wins):

```rust
GGPlot::new(data)
    .aes(Aes::new().x("day").y("count"))
    .geom_col()
    .primary_color((26, 153, 136)) // DataZoo teal — no per-chart color code
    .render_svg()?;
```

Build a whole `Theme` at runtime and compose the brand into it:

```rust
let theme = theme_minimal().with_primary((26, 153, 136));
GGPlot::new(data).aes(/* … */).geom_line().theme(theme);
```

Supply an **arbitrary sequential ramp** (e.g. a green→red risk score) instead of
the built-in viridis/brewer scales — pass explicit `(offset, color)` stops:

```rust
GGPlot::new(data)
    .aes(Aes::new().x("x").y("y").color("risk"))
    .geom_point()
    .scale_color_gradientn(vec![
        (0.0, RGBAColor::new(0, 160, 80)),   // low  = green
        (0.5, RGBAColor::new(240, 200, 0)),  // mid  = amber
        (1.0, RGBAColor::new(200, 40, 40)),  // high = red
    ]);
```

## Feature Flags

| Feature      | Default | Provides                                                    |
| ------------ | :-----: | ----------------------------------------------------------- |
| `polars`     |   yes   | `impl GGData for polars::DataFrame` + `polars` re-export     |
| `plotters`   |   yes   | plotters-backed `render_svg`, `render_png`, `save`, `ggsave`, `ggarrange_png` (implies `png`) |
| `png`        |  (yes)  | PNG encoding via `image` (pulled in by `plotters` and `canvas`) |
| `arrow`      |   no    | `impl GGData for arrow::RecordBatch` (Arrow/DuckDB input)    |
| `regression` |   no    | `stat_quantile`/`geom_quantile` + `geom_smooth` glm/rlm via anofox-regression |
| `serde`      |   no    | `theme::config::ThemeConfig` — a serde-deserialisable partial theme overlay (TOML/JSON) |
| `sf`         |   no    | `geom_sf` / `coord_sf` — render simple-features (WKT) geometry with projections; no extra deps |
| `geojson`    |   no    | read GeoJSON into a plot-ready frame (`spatial::geojson`); adds `serde_json` |
| `canvas`     |   no    | self-contained RGBA raster backend for large-N (`render_rgba`/`render_png_raster`); wasm-ok |
| `wasm`       |   no    | **deprecated** alias for `sf` (the browser bindings moved to the `crates/ggplot-rs-wasm` crate) |
| `cli`        |   no    | the `ggplot-rs` command-line tool (parquet/CSV/DuckDB → SVG/PNG), via clap + bundled DuckDB |

To skip the heavy polars and plotters dependencies (e.g. an Arrow-only service
that renders with `render_svg_native*`), disable defaults:

```toml
ggplot-rs = { version = "0.16", default-features = false, features = ["arrow"] }
```

With `default-features = false, features = ["sf"]` the whole dependency tree is
`ggplot-rs` + `indexmap` (+ its two dependencies).

## Examples

Run any example with:

```sh
cargo run --example scatter
cargo run --example histogram
cargo run --example bar_chart
cargo run --example continuous_color
cargo run --example density
cargo run --example faceted
cargo run --example loess_smooth
cargo run --example annotations
cargo run --example coord_flip
cargo run --example log_scale
cargo run --example color_palettes
cargo run --example gallery            # regenerates the gallery above
cargo run --example supplier_leadtime  # polars-free; runs with --no-default-features --features plotters
cargo run --example inventory_twin     # polars-free; SVG with --no-default-features, + PNG with plotters
```

## Dependencies

- [indexmap](https://crates.io/crates/indexmap) 2 — ordered maps for internal data
- [plotters](https://crates.io/crates/plotters) 0.3 — SVG/PNG rendering (`ab_glyph` text backend; no fontconfig) *(optional, default)*
- [image](https://crates.io/crates/image) 0.24 — in-memory PNG encoding *(optional, via `plotters`/`canvas`)*
- [polars](https://crates.io/crates/polars) 0.46 — DataFrame input *(optional, default)*
- [arrow](https://crates.io/crates/arrow) 53 — Arrow `RecordBatch` input *(optional)*
- [clap](https://crates.io/crates/clap) 4 + [duckdb](https://crates.io/crates/duckdb) 1 (bundled) — the `cli` tool *(optional)*

## License

Licensed under either of

- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)

at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

### Bundled font

Bundled fonts in `assets/fonts/` — DejaVu **Sans** (+ Bold/Oblique), **Serif** (+ Bold/Italic), and **Sans Mono** (+ Bold) — give headless rendering for `family = "serif"`/`"monospace"` and bold/italic (`element_text(face=)`) with real glyphs, no fontconfig. DejaVu Sans
is distributed under a permissive, freely-redistributable license (Bitstream Vera
+ Arev) — see [`assets/fonts/LICENSE-DejaVu.txt`](assets/fonts/LICENSE-DejaVu.txt).