ruviz 0.3.1

High-performance 2D plotting library for Rust
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
# Migrating from matplotlib to ruviz

Complete guide for Python/matplotlib users transitioning to ruviz.

## Quick Comparison

### Basic Line Plot

**Python/matplotlib**:
```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid(True)
plt.savefig('plot.png', dpi=300)
plt.show()
```

**Rust/ruviz**:
```rust
use ruviz::prelude::*;

let x: Vec<f64> = (0..100).map(|i| i as f64 * 0.1).collect();
let y: Vec<f64> = x.iter().map(|v| v.sin()).collect();

Plot::new()
    .line(&x, &y)
    .title("Sine Wave")
    .xlabel("X axis")
    .ylabel("Y axis")
    .grid(true)
    .save("plot.png")?;
```

## API Translation Table

| matplotlib | ruviz | Notes |
|------------|-------|-------|
| `plt.plot(x, y)` | `Plot::new().line(&x, &y)` | Builder pattern |
| `plt.scatter(x, y)` | `Plot::new().scatter(&x, &y)` | |
| `plt.bar(x, y)` | `Plot::new().bar(&categories, &values)` | |
| `plt.hist(data)` | `Plot::new().histogram(&data, None)` | |
| `plt.title('text')` | `.title("text")` | Method chaining |
| `plt.xlabel('text')` | `.xlabel("text")` | |
| `plt.ylabel('text')` | `.ylabel("text")` | |
| `plt.legend()` | `.legend(Position::TopRight)` | Explicit position |
| `plt.grid(True)` | `.grid(true)` | |
| `plt.xlim(0, 10)` | `.xlim(0.0, 10.0)` | |
| `plt.ylim(0, 10)` | `.ylim(0.0, 10.0)` | |
| `plt.savefig('file.png')` | `.save("file.png")?` | Returns Result |
| `plt.savefig('file.png', dpi=300)` | `.dpi(300).save("file.png")?` | |
| `plt.show()` | N/A | Save to file instead |

## Common Patterns

### Multiple Series

**matplotlib**:
```python
plt.plot(x, y1, label='Linear')
plt.plot(x, y2, label='Quadratic')
plt.plot(x, y3, label='Cubic')
plt.legend()
```

**ruviz**:
```rust
Plot::new()
    .line(&x, &y1).label("Linear")
    .line(&x, &y2).label("Quadratic")
    .line(&x, &y3).label("Cubic")
    .legend(Position::TopLeft)
    .save("multi_series.png")?;
```

### Styling

**matplotlib**:
```python
plt.plot(x, y, color='red', linewidth=2, linestyle='--', marker='o')
```

**ruviz**:
```rust
Plot::new()
    .line(&x, &y)
    .color(Color::from_rgb(255, 0, 0))
    .line_width(2.0)
    .line_style(LineStyle::Dashed)
    .marker(MarkerStyle::Circle)
    .save("styled.png")?;
```

### Subplots

**matplotlib**:
```python
fig, axes = plt.subplots(2, 2, figsize=(12, 9))
axes[0, 0].plot(x, y1)
axes[0, 0].set_title('Plot 1')
axes[0, 1].scatter(x, y2)
axes[0, 1].set_title('Plot 2')
fig.suptitle('Multiple Plots')
plt.savefig('subplots.png')
```

**ruviz**:
```rust
let plot1 = Plot::new().line(&x, &y1).title("Plot 1").end_series();
let plot2 = Plot::new().scatter(&x, &y2).title("Plot 2").end_series();
let plot3 = Plot::new().bar(&cats, &vals).title("Plot 3").end_series();
let plot4 = Plot::new().histogram(&data, None).title("Plot 4").end_series();

subplots(2, 2, 1200, 900)?
    .subplot(0, 0, plot1)?
    .subplot(0, 1, plot2)?
    .subplot(1, 0, plot3)?
    .subplot(1, 1, plot4)?
    .suptitle("Multiple Plots")
    .save("subplots.png")?;
```

### Themes/Styles

**matplotlib**:
```python
plt.style.use('seaborn')
# or
plt.style.use('ggplot')
# or
import seaborn as sns
sns.set_theme()
```

**ruviz**:
```rust
Plot::new()
    .theme(Theme::seaborn())
    .line(&x, &y)
    .save("themed.png")?;

// Available themes:
// - Theme::light() (default)
// - Theme::dark()
// - Theme::publication() (for papers)
// - Theme::seaborn() (matplotlib seaborn style)
```

## Feature Comparison

### Supported in ruviz ✅

| Feature | matplotlib | ruviz |
|---------|------------|-------|
| Line plots | `plot()` | `.line()` |
| Scatter plots | `scatter()` | `.scatter()` |
| Bar charts | `bar()` | `.bar()` |
| Histograms | `hist()` | `.histogram()` |
| Box plots | `boxplot()` | `.boxplot()` |
| Multiple series |||
| Legends | `legend()` | `.legend()` |
| Grid | `grid()` | `.grid()` |
| Titles/labels |||
| Custom colors |||
| Line styles |||
| Markers |||
| Subplots | `subplots()` | `subplots()` |
| Themes | `style.use()` | `.theme()` |
| DPI control | `dpi=` | `.dpi()` |
| Figure size | `figsize=` | `.dimensions()` |
| PNG export | `savefig()` | `.save()` |

### Support Snapshot ⚠️

| Feature | matplotlib | ruviz Status |
|---------|------------|--------------|
| SVG export | `savefig('file.svg')` | Supported via `.export_svg("file.svg")?` |
| Heatmaps | `imshow()`, `pcolormesh()` | Supported via `.heatmap(...)` |
| Contour plots | `contour()` | Supported via `.contour(...)` |
| 3D plots | `mpl_toolkits.mplot3d` | Planned v1.0+ |
| Interactive plots | `%matplotlib notebook` | Experimental via `show_interactive(plot).await` |
| Polar plots | `projection='polar'` | Supported via `.polar_line(...)` |
| Animations | `FuncAnimation` | Supported with the `record!` macro |

### Different Approach 🔄

| Feature | matplotlib | ruviz Equivalent |
|---------|------------|------------------|
| Interactive display | `plt.show()` | Save to file, view externally |
| Jupyter integration | `%matplotlib inline` | Save + display markdown cell |
| Global state | `plt.plot()` then `plt.title()` | Builder pattern (no global state) |
| Automatic figure mgmt | Implicit figure creation | Explicit `Plot::new()` |

## Data Types

### numpy arrays → Rust vectors

**matplotlib**:
```python
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
```

**ruviz with ndarray** (closest to numpy):
```rust
use ndarray::Array1;

let x = Array1::linspace(0.0, 10.0, 100);
let y = x.mapv(|v| v.sin());

Plot::new()
    .line(&x, &y)
    .save("plot.png")?;
```

**ruviz with Vec** (standard Rust):
```rust
let x: Vec<f64> = (0..100).map(|i| i as f64 * 0.1).collect();
let y: Vec<f64> = x.iter().map(|v| v.sin()).collect();

Plot::new()
    .line(&x, &y)
    .save("plot.png")?;
```

### pandas → polars

**matplotlib with pandas**:
```python
import pandas as pd
df = pd.read_csv('data.csv')
plt.plot(df['x'], df['y'])
```

**ruviz with polars**:
```rust
use polars::prelude::*;

let df = CsvReader::from_path("data.csv")?.finish()?;
let x = df.column("x")?.f64()?;
let y = df.column("y")?.f64()?;

Plot::new()
    .line(x, y)
    .save("plot.png")?;
```

## Performance Comparison

| Task | matplotlib | ruviz | Speedup |
|------|------------|-------|---------|
| 1K points | ~5ms | ~5ms | 1x |
| 10K points | ~50ms | ~18ms | 2.8x |
| 100K points | ~500ms | ~100ms | 5x |
| 1M points | ~5s | ~720ms | 7x |
| 10M points | ~60s | ~2s | 30x |

*Benchmarks on AMD Ryzen 9 5950X, Ubuntu 22.04*

## Migration Examples

### Example 1: Scientific Plot

**Before (Python)**:
```python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 1000)
y_sin = np.sin(x)
y_cos = np.cos(x)

plt.figure(figsize=(10, 6), dpi=300)
plt.plot(x, y_sin, 'b-', label='sin(x)', linewidth=2)
plt.plot(x, y_cos, 'r--', label='cos(x)', linewidth=2)
plt.title('Trigonometric Functions', fontsize=16)
plt.xlabel('x (radians)', fontsize=12)
plt.ylabel('y', fontsize=12)
plt.legend(loc='upper right')
plt.grid(True, alpha=0.3)
plt.savefig('trig.png', dpi=300, bbox_inches='tight')
```

**After (Rust)**:
```rust
use ruviz::prelude::*;
use std::f64::consts::PI;

let x: Vec<f64> = (0..1000).map(|i| i as f64 * 2.0 * PI / 999.0).collect();
let y_sin: Vec<f64> = x.iter().map(|v| v.sin()).collect();
let y_cos: Vec<f64> = x.iter().map(|v| v.cos()).collect();

Plot::new()
    .dimensions(1000, 600)
    .dpi(300)
    .line(&x, &y_sin)
        .color(Color::from_rgb(0, 0, 255))
        .line_width(2.0)
        .label("sin(x)")
    .line(&x, &y_cos)
        .color(Color::from_rgb(255, 0, 0))
        .line_style(LineStyle::Dashed)
        .line_width(2.0)
        .label("cos(x)")
    .title("Trigonometric Functions")
    .xlabel("x (radians)")
    .ylabel("y")
    .legend(Position::TopRight)
    .grid(true)
    .save("trig.png")?;
```

### Example 2: Data Analysis

**Before (Python)**:
```python
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('measurements.csv')
grouped = df.groupby('category')['value'].mean()

plt.bar(grouped.index, grouped.values)
plt.title('Average Values by Category')
plt.xlabel('Category')
plt.ylabel('Average Value')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('analysis.png')
```

**After (Rust)**:
```rust
use ruviz::prelude::*;
use polars::prelude::*;

let df = CsvReader::from_path("measurements.csv")?.finish()?;

let grouped = df
    .lazy()
    .groupby([col("category")])
    .agg([col("value").mean()])
    .collect()?;

let categories: Vec<&str> = grouped
    .column("category")?
    .utf8()?
    .into_iter()
    .map(|opt| opt.unwrap_or(""))
    .collect();

let values: Vec<f64> = grouped
    .column("value")?
    .f64()?
    .into_iter()
    .map(|opt| opt.unwrap_or(0.0))
    .collect();

Plot::new()
    .bar(&categories, &values)
    .title("Average Values by Category")
    .xlabel("Category")
    .ylabel("Average Value")
    .save("analysis.png")?;
```

## FAQ

### Q: Can I use ruviz in Jupyter notebooks?
**A**: Not directly (no Python bindings yet). However, you can:
1. Save plots to files in Rust
2. Display them in Jupyter using `IPython.display.Image()`
3. Or use PyO3 to create Python bindings (community contribution welcome!)

### Q: How do I display plots interactively?
**A**: Current focus is file output. For interactive:
1. Enable `interactive` or `interactive-gpu`
2. Build a `Plot`
3. Call `show_interactive(plot).await`

### Q: What about animations?
**A**: Animations are available behind the `animation` feature via the `record!` macro.

### Q: Can I customize colors like matplotlib's colormap?
**A**: Yes, but differently:
```rust
// Custom colors
.color(Color::from_rgb(255, 128, 0))
.color(Color::from_hex("#FF8000")?)

let viridis_like = Theme::builder()
    .palette([
        Color::from_hex("#440154").unwrap(),
        Color::from_hex("#31688e").unwrap(),
        Color::from_hex("#35b779").unwrap(),
        Color::from_hex("#fde725").unwrap(),
    ])
    .build();
```

### Q: Performance tips for large datasets?
**A**:
1. Use `features = ["parallel"]` for >10K points
2. Use `features = ["parallel", "simd"]` for >100K points
3. DataShader automatically activates for >1M points
4. See [Performance Guide]../guide/08_performance.md

## Migration Checklist

- [ ] Install Rust and cargo
- [ ] Add `ruviz = "0.1"` to `Cargo.toml`
- [ ] Convert numpy arrays to `Vec<f64>` or `ndarray`
- [ ] Replace `plt.plot()` with `Plot::new().line()`
- [ ] Change `plt.savefig()` to `.save()?`
- [ ] Handle `Result` types with `?` operator
- [ ] Update data loading (pandas → polars if needed)
- [ ] Test with small dataset first
- [ ] Optimize with appropriate backend features
- [ ] Update CI/CD to compile Rust code

## Resources

- **[ruviz User Guide]../guide/README.md** - Complete documentation
- **[Examples]../../examples/** - Working code samples
- **[API Docs]https://docs.rs/ruviz** - Full API reference
- **[Quickstart]../QUICKSTART.md** - 5-minute tutorial

## Getting Help

- **GitHub Issues**: Bug reports and feature requests
- **GitHub Discussions**: Questions and community support
- **Examples Directory**: Real-world usage patterns

Ready to start? Follow the [User Guide](../guide/README.md) for step-by-step instructions.