-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotting.py
More file actions
774 lines (691 loc) · 23.8 KB
/
plotting.py
File metadata and controls
774 lines (691 loc) · 23.8 KB
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
"""
Plotly Express plotting functions for DataArray objects.
"""
from __future__ import annotations
import warnings
from typing import TYPE_CHECKING, Any
import numpy as np
import numpy.typing as npt
import plotly.express as px
from xarray_plotly.common import (
Colors,
SlotValue,
assign_slots,
auto,
build_labels,
get_label,
get_value_col,
resolve_colors,
to_dataframe,
)
from xarray_plotly.figures import (
_iter_all_traces,
)
if TYPE_CHECKING:
import plotly.graph_objects as go
from xarray import DataArray
def line(
darray: DataArray,
*,
x: SlotValue = auto,
color: SlotValue = auto,
line_dash: SlotValue = auto,
symbol: SlotValue = auto,
facet_col: SlotValue = auto,
facet_row: SlotValue = auto,
animation_frame: SlotValue = auto,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create an interactive line plot from a DataArray.
The y-axis shows DataArray values. Dimensions fill slots in order:
x -> color -> line_dash -> symbol -> facet_col -> facet_row -> animation_frame
Parameters
----------
darray
The DataArray to plot.
x
Dimension for x-axis. Default: first dimension.
color
Dimension for color grouping. Default: second dimension.
line_dash
Dimension for line dash style. Default: third dimension.
symbol
Dimension for marker symbol. Default: fourth dimension.
facet_col
Dimension for subplot columns. Default: fifth dimension.
facet_row
Dimension for subplot rows. Default: sixth dimension.
animation_frame
Dimension for animation. Default: seventh dimension.
colors
Unified color specification. Can be:
- A named continuous scale (e.g., "Viridis")
- A named discrete palette (e.g., "D3", "Plotly")
- A list of colors (e.g., ["red", "blue", "green"])
- A dict mapping values to colors (e.g., {"A": "red", "B": "blue"})
Explicit color_* kwargs in px_kwargs take precedence.
**px_kwargs
Additional arguments passed to `plotly.express.line()`.
Returns
-------
plotly.graph_objects.Figure
"""
slots = assign_slots(
list(darray.dims),
"line",
x=x,
color=color,
line_dash=line_dash,
symbol=symbol,
facet_col=facet_col,
facet_row=facet_row,
animation_frame=animation_frame,
)
px_kwargs = resolve_colors(colors, px_kwargs, color_dim=slots.get("color"), darray=darray)
df = to_dataframe(darray)
value_col = get_value_col(darray)
labels = {**build_labels(darray, slots, value_col), **px_kwargs.pop("labels", {})}
return px.line(
df,
x=slots.get("x"),
y=value_col,
color=slots.get("color"),
line_dash=slots.get("line_dash"),
symbol=slots.get("symbol"),
facet_col=slots.get("facet_col"),
facet_row=slots.get("facet_row"),
animation_frame=slots.get("animation_frame"),
labels=labels,
**px_kwargs,
)
def bar(
darray: DataArray,
*,
x: SlotValue = auto,
color: SlotValue = auto,
pattern_shape: SlotValue = auto,
facet_col: SlotValue = auto,
facet_row: SlotValue = auto,
animation_frame: SlotValue = auto,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create an interactive bar chart from a DataArray.
The y-axis shows DataArray values. Dimensions fill slots in order:
x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame
Parameters
----------
darray
The DataArray to plot.
x
Dimension for x-axis. Default: first dimension.
color
Dimension for color grouping. Default: second dimension.
pattern_shape
Dimension for bar fill pattern. Default: third dimension.
facet_col
Dimension for subplot columns. Default: fourth dimension.
facet_row
Dimension for subplot rows. Default: fifth dimension.
animation_frame
Dimension for animation. Default: sixth dimension.
colors
Unified color specification. Can be:
- A named continuous scale (e.g., "Viridis")
- A named discrete palette (e.g., "D3", "Plotly")
- A list of colors (e.g., ["red", "blue", "green"])
- A dict mapping values to colors (e.g., {"A": "red", "B": "blue"})
Explicit color_* kwargs in px_kwargs take precedence.
**px_kwargs
Additional arguments passed to `plotly.express.bar()`.
Returns
-------
plotly.graph_objects.Figure
"""
px_kwargs = resolve_colors(colors, px_kwargs)
slots = assign_slots(
list(darray.dims),
"bar",
x=x,
color=color,
pattern_shape=pattern_shape,
facet_col=facet_col,
facet_row=facet_row,
animation_frame=animation_frame,
)
df = to_dataframe(darray)
value_col = get_value_col(darray)
labels = {**build_labels(darray, slots, value_col), **px_kwargs.pop("labels", {})}
return px.bar(
df,
x=slots.get("x"),
y=value_col,
color=slots.get("color"),
pattern_shape=slots.get("pattern_shape"),
facet_col=slots.get("facet_col"),
facet_row=slots.get("facet_row"),
animation_frame=slots.get("animation_frame"),
labels=labels,
**px_kwargs,
)
def _classify_trace_sign(y_values: npt.ArrayLike) -> str:
"""Classify a trace as 'positive', 'negative', or 'mixed' based on its values."""
y_arr = np.asarray(y_values)
y_clean = y_arr[np.isfinite(y_arr) & (np.abs(y_arr) > 1e-9)]
if len(y_clean) == 0:
return "zero"
has_pos = bool(np.any(y_clean > 0))
has_neg = bool(np.any(y_clean < 0))
if has_pos and has_neg:
return "mixed"
elif has_neg:
return "negative"
elif has_pos:
return "positive"
return "zero"
def _style_traces_as_bars(fig: go.Figure) -> None:
"""Style area chart traces to look like bar charts with proper pos/neg stacking.
Classifies each trace (by name) across all data and animation frames,
then assigns stackgroups: positive traces stack upward, negative stack downward.
"""
# Collect all traces (main + animation frames)
all_traces = list(_iter_all_traces(fig))
# Classify each trace name by aggregating sign info across all occurrences
sign_flags: dict[str, dict[str, bool]] = {}
for trace in all_traces:
if trace.name not in sign_flags:
sign_flags[trace.name] = {"has_pos": False, "has_neg": False}
if trace.y is not None and len(trace.y) > 0:
y_arr = np.asarray(trace.y)
y_clean = y_arr[np.isfinite(y_arr) & (np.abs(y_arr) > 1e-9)]
if len(y_clean) > 0:
if np.any(y_clean > 0):
sign_flags[trace.name]["has_pos"] = True
if np.any(y_clean < 0):
sign_flags[trace.name]["has_neg"] = True
# Build classification map
class_map: dict[str, str] = {}
mixed_traces: list[str] = []
for name, flags in sign_flags.items():
if flags["has_pos"] and flags["has_neg"]:
class_map[name] = "mixed"
mixed_traces.append(name)
elif flags["has_neg"]:
class_map[name] = "negative"
elif flags["has_pos"]:
class_map[name] = "positive"
else:
class_map[name] = "zero"
# Warn about mixed traces
if mixed_traces:
warnings.warn(
f"fast_bar: traces {mixed_traces} have mixed positive/negative values "
"and cannot be stacked. They are shown as dashed lines. "
"Consider using bar() for proper stacking of mixed data.",
UserWarning,
stacklevel=3,
)
# Apply styling to all traces
for trace in all_traces:
color = trace.line.color
cls = class_map.get(trace.name, "positive")
if cls in ("positive", "negative"):
trace.stackgroup = cls
trace.fillcolor = color
trace.line = {"width": 0, "color": color, "shape": "hv"}
elif cls == "mixed":
# Mixed: no stacking, show as dashed line
trace.stackgroup = None
trace.fill = None
trace.line = {"width": 2, "color": color, "shape": "hv", "dash": "dash"}
else: # zero
trace.stackgroup = None
trace.fill = None
trace.line = {"width": 0, "color": color, "shape": "hv"}
def fast_bar(
darray: DataArray,
*,
x: SlotValue = auto,
color: SlotValue = auto,
facet_col: SlotValue = auto,
facet_row: SlotValue = auto,
animation_frame: SlotValue = auto,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create a bar-like chart using stacked areas for better performance.
Uses `px.area` with stepped lines and no outline to create a bar-like
appearance. Renders faster than `bar()` for large datasets because it
uses a single polygon per trace instead of individual rectangles.
The y-axis shows DataArray values. Dimensions fill slots in order:
x -> color -> facet_col -> facet_row -> animation_frame
Traces are classified by their values: purely positive traces stack upward,
purely negative traces stack downward. Traces with mixed signs are shown
as dashed lines without stacking.
Parameters
----------
darray
The DataArray to plot.
x
Dimension for x-axis. Default: first dimension.
color
Dimension for color/stacking. Default: second dimension.
facet_col
Dimension for subplot columns. Default: third dimension.
facet_row
Dimension for subplot rows. Default: fourth dimension.
animation_frame
Dimension for animation. Default: fifth dimension.
colors
Unified color specification. Can be:
- A named continuous scale (e.g., "Viridis")
- A named discrete palette (e.g., "D3", "Plotly")
- A list of colors (e.g., ["red", "blue", "green"])
- A dict mapping values to colors (e.g., {"A": "red", "B": "blue"})
Explicit color_* kwargs in px_kwargs take precedence.
**px_kwargs
Additional arguments passed to `plotly.express.area()`.
Returns
-------
plotly.graph_objects.Figure
"""
slots = assign_slots(
list(darray.dims),
"fast_bar",
x=x,
color=color,
facet_col=facet_col,
facet_row=facet_row,
animation_frame=animation_frame,
)
px_kwargs = resolve_colors(colors, px_kwargs, color_dim=slots.get("color"), darray=darray)
df = to_dataframe(darray)
value_col = get_value_col(darray)
labels = {**build_labels(darray, slots, value_col), **px_kwargs.pop("labels", {})}
fig = px.area(
df,
x=slots.get("x"),
y=value_col,
color=slots.get("color"),
facet_col=slots.get("facet_col"),
facet_row=slots.get("facet_row"),
animation_frame=slots.get("animation_frame"),
line_shape="hv",
labels=labels,
**px_kwargs,
)
_style_traces_as_bars(fig)
return fig
def area(
darray: DataArray,
*,
x: SlotValue = auto,
color: SlotValue = auto,
pattern_shape: SlotValue = auto,
facet_col: SlotValue = auto,
facet_row: SlotValue = auto,
animation_frame: SlotValue = auto,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create an interactive stacked area chart from a DataArray.
The y-axis shows DataArray values. Dimensions fill slots in order:
x -> color -> pattern_shape -> facet_col -> facet_row -> animation_frame
Parameters
----------
darray
The DataArray to plot.
x
Dimension for x-axis. Default: first dimension.
color
Dimension for color/stacking. Default: second dimension.
pattern_shape
Dimension for fill pattern. Default: third dimension.
facet_col
Dimension for subplot columns. Default: fourth dimension.
facet_row
Dimension for subplot rows. Default: fifth dimension.
animation_frame
Dimension for animation. Default: sixth dimension.
colors
Unified color specification. Can be:
- A named continuous scale (e.g., "Viridis")
- A named discrete palette (e.g., "D3", "Plotly")
- A list of colors (e.g., ["red", "blue", "green"])
- A dict mapping values to colors (e.g., {"A": "red", "B": "blue"})
Explicit color_* kwargs in px_kwargs take precedence.
**px_kwargs
Additional arguments passed to `plotly.express.area()`.
Returns
-------
plotly.graph_objects.Figure
"""
slots = assign_slots(
list(darray.dims),
"area",
x=x,
color=color,
pattern_shape=pattern_shape,
facet_col=facet_col,
facet_row=facet_row,
animation_frame=animation_frame,
)
px_kwargs = resolve_colors(colors, px_kwargs, color_dim=slots.get("color"), darray=darray)
df = to_dataframe(darray)
value_col = get_value_col(darray)
labels = {**build_labels(darray, slots, value_col), **px_kwargs.pop("labels", {})}
return px.area(
df,
x=slots.get("x"),
y=value_col,
color=slots.get("color"),
pattern_shape=slots.get("pattern_shape"),
facet_col=slots.get("facet_col"),
facet_row=slots.get("facet_row"),
animation_frame=slots.get("animation_frame"),
labels=labels,
**px_kwargs,
)
def box(
darray: DataArray,
*,
x: SlotValue = auto,
color: SlotValue = None,
facet_col: SlotValue = None,
facet_row: SlotValue = None,
animation_frame: SlotValue = None,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create an interactive box plot from a DataArray.
The y-axis shows DataArray values. By default, only x is auto-assigned;
other dimensions are aggregated into the box statistics.
Dimensions fill slots in order: x -> color -> facet_col -> facet_row -> animation_frame
Parameters
----------
darray
The DataArray to plot.
x
Dimension for x-axis categories. Default: first dimension.
color
Dimension for color grouping. Default: None (aggregated).
facet_col
Dimension for subplot columns. Default: None (aggregated).
facet_row
Dimension for subplot rows. Default: None (aggregated).
animation_frame
Dimension for animation. Default: None (aggregated).
colors
Unified color specification. Can be:
- A named continuous scale (e.g., "Viridis")
- A named discrete palette (e.g., "D3", "Plotly")
- A list of colors (e.g., ["red", "blue", "green"])
- A dict mapping values to colors (e.g., {"A": "red", "B": "blue"})
Explicit color_* kwargs in px_kwargs take precedence.
**px_kwargs
Additional arguments passed to `plotly.express.box()`.
Returns
-------
plotly.graph_objects.Figure
"""
slots = assign_slots(
list(darray.dims),
"box",
allow_unassigned=True,
x=x,
color=color,
facet_col=facet_col,
facet_row=facet_row,
animation_frame=animation_frame,
)
px_kwargs = resolve_colors(colors, px_kwargs, color_dim=slots.get("color"), darray=darray)
df = to_dataframe(darray)
value_col = get_value_col(darray)
labels = {**build_labels(darray, slots, value_col), **px_kwargs.pop("labels", {})}
return px.box(
df,
x=slots.get("x"),
y=value_col,
color=slots.get("color"),
facet_col=slots.get("facet_col"),
facet_row=slots.get("facet_row"),
animation_frame=slots.get("animation_frame"),
labels=labels,
**px_kwargs,
)
def scatter(
darray: DataArray,
*,
x: SlotValue = auto,
y: SlotValue | str = "value",
color: SlotValue = auto,
symbol: SlotValue = auto,
facet_col: SlotValue = auto,
facet_row: SlotValue = auto,
animation_frame: SlotValue = auto,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create an interactive scatter plot from a DataArray.
By default, y-axis shows DataArray values. Set y to a dimension name
for dimension-vs-dimension plots (e.g., lat vs lon colored by value).
Dimensions fill slots in order:
x -> color -> symbol -> facet_col -> facet_row -> animation_frame
Parameters
----------
darray
The DataArray to plot.
x
Dimension for x-axis. Default: first dimension.
y
What to plot on y-axis. Default "value" uses DataArray values.
Can be a dimension name for dimension vs dimension plots.
color
Dimension for color grouping. Default: second dimension.
Use "value" to color by DataArray values (useful with y=dimension).
symbol
Dimension for marker symbol. Default: third dimension.
facet_col
Dimension for subplot columns. Default: fourth dimension.
facet_row
Dimension for subplot rows. Default: fifth dimension.
animation_frame
Dimension for animation. Default: sixth dimension.
colors
Unified color specification. Can be:
- A named continuous scale (e.g., "Viridis")
- A named discrete palette (e.g., "D3", "Plotly")
- A list of colors (e.g., ["red", "blue", "green"])
- A dict mapping values to colors (e.g., {"A": "red", "B": "blue"})
Explicit color_* kwargs in px_kwargs take precedence.
**px_kwargs
Additional arguments passed to `plotly.express.scatter()`.
Returns
-------
plotly.graph_objects.Figure
"""
px_kwargs = resolve_colors(colors, px_kwargs)
# If y is a dimension, exclude it from slot assignment
y_is_dim = y != "value" and y in darray.dims
dims_for_slots = [d for d in darray.dims if d != y] if y_is_dim else list(darray.dims)
slots = assign_slots(
dims_for_slots,
"scatter",
x=x,
color=color,
symbol=symbol,
facet_col=facet_col,
facet_row=facet_row,
animation_frame=animation_frame,
)
df = to_dataframe(darray)
value_col = get_value_col(darray)
# Resolve y and color columns (may be "value" -> actual column name)
y_col = value_col if y == "value" else y
color_col = value_col if slots.get("color") == "value" else slots.get("color")
# Build labels
labels = {**build_labels(darray, slots, value_col), **px_kwargs.pop("labels", {})}
if y_is_dim and str(y) not in labels:
labels[str(y)] = get_label(darray, y)
return px.scatter(
df,
x=slots.get("x"),
y=y_col,
color=color_col,
symbol=slots.get("symbol"),
facet_col=slots.get("facet_col"),
facet_row=slots.get("facet_row"),
animation_frame=slots.get("animation_frame"),
labels=labels,
**px_kwargs,
)
def imshow(
darray: DataArray,
*,
x: SlotValue = auto,
y: SlotValue = auto,
facet_col: SlotValue = auto,
animation_frame: SlotValue = auto,
robust: bool = False,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create an interactive heatmap from a DataArray.
Both x and y are dimensions. Dimensions fill slots in order:
y (rows) -> x (columns) -> facet_col -> animation_frame
.. note::
**Difference from plotly.express.imshow**: By default, color bounds
(zmin/zmax) are computed from the **entire dataset**, ensuring
consistent coloring across animation frames and facets. In contrast,
``px.imshow`` auto-scales each frame independently, which can make
animations visually confusing. Set ``zmin`` and ``zmax`` explicitly
to override this behavior.
Parameters
----------
darray
The DataArray to plot.
x
Dimension for x-axis (columns). Default: second dimension.
y
Dimension for y-axis (rows). Default: first dimension.
facet_col
Dimension for subplot columns. Default: third dimension.
animation_frame
Dimension for animation. Default: fourth dimension.
robust
If True, compute color bounds using 2nd and 98th percentiles
for robustness against outliers. Default: False (uses min/max).
colors
Unified color specification. For imshow, typically a named
continuous scale (e.g., "Viridis", "RdBu"). Lists and dicts
are not applicable for heatmaps.
Explicit color_continuous_scale in px_kwargs takes precedence.
**px_kwargs
Additional arguments passed to `plotly.express.imshow()`.
Use `zmin` and `zmax` to manually set color scale bounds.
Returns
-------
plotly.graph_objects.Figure
"""
px_kwargs = resolve_colors(colors, px_kwargs)
slots = assign_slots(
list(darray.dims),
"imshow",
y=y,
x=x,
facet_col=facet_col,
animation_frame=animation_frame,
)
# Transpose to: y (rows), x (cols), facet_col, animation_frame
transpose_order = [
slots[k] for k in ("y", "x", "facet_col", "animation_frame") if slots.get(k) is not None
]
plot_data = darray.transpose(*transpose_order) if transpose_order else darray
# Compute global color bounds if not provided
if "zmin" not in px_kwargs or "zmax" not in px_kwargs:
values = plot_data.values
if robust:
# Use percentiles for outlier robustness
zmin = float(np.nanpercentile(values, 2))
zmax = float(np.nanpercentile(values, 98))
else:
# Use global min/max across all data
zmin = float(np.nanmin(values))
zmax = float(np.nanmax(values))
px_kwargs.setdefault("zmin", zmin)
px_kwargs.setdefault("zmax", zmax)
return px.imshow(
plot_data,
facet_col=slots.get("facet_col"),
animation_frame=slots.get("animation_frame"),
**px_kwargs,
)
def pie(
darray: DataArray,
*,
names: SlotValue = auto,
color: SlotValue = None,
facet_col: SlotValue = auto,
facet_row: SlotValue = auto,
colors: Colors = None,
**px_kwargs: Any,
) -> go.Figure:
"""
Create an interactive pie chart from a DataArray.
The values are the DataArray values. Dimensions fill slots in order:
names -> facet_col -> facet_row
Parameters
----------
darray
The DataArray to plot.
names
Dimension for pie slice names/categories. Default: first dimension.
color
Dimension for color grouping. Default: None (uses names).
facet_col
Dimension for subplot columns. Default: second dimension.
facet_row
Dimension for subplot rows. Default: third dimension.
colors
Unified color specification. Can be:
- A named discrete palette (e.g., "D3", "Plotly")
- A list of colors (e.g., ["red", "blue", "green"])
- A dict mapping values to colors (e.g., {"A": "red", "B": "blue"})
Explicit color_* kwargs in px_kwargs take precedence.
**px_kwargs
Additional arguments passed to `plotly.express.pie()`.
Returns
-------
plotly.graph_objects.Figure
"""
slots = assign_slots(
list(darray.dims),
"pie",
names=names,
facet_col=facet_col,
facet_row=facet_row,
)
px_kwargs = resolve_colors(colors, px_kwargs, color_dim=slots.get("names"), darray=darray)
df = to_dataframe(darray)
value_col = get_value_col(darray)
labels = {**build_labels(darray, slots, value_col), **px_kwargs.pop("labels", {})}
# Use names dimension for color if not explicitly set
color_col = color if color is not None else slots.get("names")
return px.pie(
df,
names=slots.get("names"),
values=value_col,
color=color_col,
facet_col=slots.get("facet_col"),
facet_row=slots.get("facet_row"),
labels=labels,
**px_kwargs,
)