Srihari Thyagarajan commited on
Commit
8cc48bf
·
unverified ·
2 Parent(s): 8f7960d 19293d8

Merge pull request #78 from etrotta/main

Browse files
Files changed (2) hide show
  1. .gitignore +3 -0
  2. polars/05_reactive_plots.py +552 -0
.gitignore CHANGED
@@ -170,5 +170,8 @@ cython_debug/
170
  # PyPI configuration file
171
  .pypirc
172
 
 
 
 
173
  # Generated site content
174
  _site/
 
170
  # PyPI configuration file
171
  .pypirc
172
 
173
+ # Marimo specific
174
+ __marimo__
175
+
176
  # Generated site content
177
  _site/
polars/05_reactive_plots.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "marimo",
5
+ # "numpy==2.2.3",
6
+ # "plotly[express]==6.0.0",
7
+ # "polars==1.27.1",
8
+ # "statsmodels==0.14.4",
9
+ # ]
10
+ # ///
11
+
12
+ import marimo
13
+
14
+ __generated_with = "0.12.10"
15
+ app = marimo.App(width="medium")
16
+
17
+
18
+ @app.cell(hide_code=True)
19
+ def _(mo):
20
+ mo.md(
21
+ """
22
+ # Reactive Plots
23
+
24
+ _By [etrotta](https://github.com/etrotta)._
25
+
26
+ This tutorial covers Data Visualisation basics using marimo, [polars](https://docs.pola.rs/) and [plotly](https://plotly.com/python/plotly-express/).
27
+ It shows how to load data, explore and visualise it, then use User Interface elements (including the plots themselves) to filter and select data for more refined analysis.
28
+
29
+ We will be using a [Spotify Tracks dataset](https://huggingface.co/datasets/maharshipandya/spotify-tracks-dataset). Before you write any code yourself, I recommend taking some time to understand the data you're working with, from which columns are available to what are their possible values, as well as more abstract details such as the scope, coverage and intended uses of the dataset.
30
+
31
+ Note that this dataset does not contains data about ***all*** tracks, you can try using a larger dataset such as [bigdata-pw/Spotify](https://huggingface.co/datasets/bigdata-pw/Spotify), but I'm sticking with the smaller one to keep the notebook size manageable for most users.
32
+ """
33
+ )
34
+ return
35
+
36
+
37
+ @app.cell
38
+ def _(pl):
39
+ # You can read directly from the Hugging Face dataset, in which case polars will only read the necessary data:
40
+ repo_id, branch, file_path = (
41
+ "maharshipandya/spotify-tracks-dataset",
42
+ "~parquet",
43
+ "default/train/0000.parquet",
44
+ )
45
+ URL = f"hf://datasets/{repo_id}@{branch}/{file_path}"
46
+ lz = pl.scan_parquet(URL)
47
+ # Or save to a local file first if you want to avoid downloading it each time you run:
48
+ # file_path = "spotify-tracks.parquet"
49
+ # lz = pl.scan_parquet(file_path)
50
+ return URL, branch, file_path, lz, repo_id
51
+
52
+
53
+ @app.cell(hide_code=True)
54
+ def _(mo):
55
+ mo.md(
56
+ """
57
+ You should always take a look at the data you are working on before actually doing any operations on it - for data coming from sources such as HuggingFace or Kaggle you can preview it via their websites, and optionally filter or do some transformations before downloading.
58
+
59
+ The [Polars Lazy API](https://docs.pola.rs/user-guide/lazy/) allows for you define operations before loading the data, and polars will optimize the plan in order to avoid doing unnecessary operations or loading data we do not care about.
60
+
61
+ Let's say that looking at the dataset's preview in the Data Viewer, we decided we do not want the Unnamed column (which appears to be the row index), nor do we care about the original ID, and we only want non-explicit tracks.
62
+ """
63
+ )
64
+ return
65
+
66
+
67
+ @app.cell
68
+ def _(lz, pl):
69
+ df = (
70
+ lz
71
+ # Filter data we consider relevant (somewhat arbitrary in this example)
72
+ .filter(pl.col("explicit") == False)
73
+ .drop("Unnamed: 0", "track_id", "explicit")
74
+ .with_columns(
75
+ # Perform whichever transformations you want (again somewhat arbitrary in this example)
76
+ # Convert the duration from milliseconds to seconds (int)
77
+ pl.col("duration_ms").floordiv(1_000).alias("duration_seconds"),
78
+ # Convert the popularity from an integer 0 ~ 100 to a percentage 0 ~ 1.0
79
+ pl.col("popularity").truediv(100),
80
+ )
81
+ # lastly, download (if needed) and collect into memory
82
+ .collect()
83
+ )
84
+ df
85
+ return (df,)
86
+
87
+
88
+ @app.cell(hide_code=True)
89
+ def _(mo):
90
+ mo.md(
91
+ r"""
92
+ When you start exploring a dataset, some of the first things to do may include:
93
+
94
+ - investigating any values that seem weird
95
+ - verifying if there could be issues in the data
96
+ - checking for potential bugs in our pipelines
97
+ - ensuring you understand the data correctly, including its relationships and edge cases
98
+
99
+ For example, the "min" value for the duration column is zero, and the max is over an hour. Why is that?
100
+ """
101
+ )
102
+ return
103
+
104
+
105
+ @app.cell(disabled=True)
106
+ def _(df, pl):
107
+ # We *could* just filter some of the rows and look at them as a table, for example...
108
+ pl.concat([df.sort("duration_ms").head(5), df.sort("duration_ms", descending=True).head(5)])
109
+ # But creating a visualisation for this helps paint the full picture of how the data is distributed, rather than focusing *only* on some outiers
110
+ return
111
+
112
+
113
+ @app.cell(hide_code=True)
114
+ def _(mo):
115
+ mo.md(
116
+ r"""
117
+ For this Notebook we will be using [plotly](https://plotly.com/python), but Marimo also [supports other plotting libraries](https://docs.marimo.io/guides/working_with_data/plotting/).
118
+
119
+ Let's visualize it using a [bar chart](https://plotly.com/python/bar-charts/) and get a feel for which region makes sense to focus on for our analysis
120
+ """
121
+ )
122
+ return
123
+
124
+
125
+ @app.cell
126
+ def _(df, mo, px):
127
+ duration_counts = df.group_by("duration_seconds").len("count")
128
+ fig = px.bar(duration_counts, x="duration_seconds", y="count")
129
+ fig.update_layout(selectdirection="h")
130
+ plot = mo.ui.plotly(fig)
131
+ plot
132
+ return duration_counts, fig, plot
133
+
134
+
135
+ @app.cell(hide_code=True)
136
+ def _(mo):
137
+ mo.md(
138
+ """
139
+ Note how there are a few outliers with extremely little duration (less than 2 minutes) and a few with extremely long duration (more than 6 minutes)
140
+
141
+ You can select a region in the graph by clicking and dragging, which can later be used to filter or transform data. In this Notebook we set a default if there is no selection, but you should try selecting a region yourself.
142
+
143
+ We will focus on those within that middle ground from around 120 seconds to 360 seconds, but you can play around with it a bit and see how the results change if you move the Selection region. Perhaps you can even find some Classical songs?
144
+ """
145
+ )
146
+ return
147
+
148
+
149
+ @app.cell
150
+ def _(pl, plot):
151
+ # The format of plot.value may vary depending on which kind of plot you are working with, let's see what we have for this case:
152
+ pl.DataFrame(plot.value)
153
+ return
154
+
155
+
156
+ @app.cell
157
+ def _(df, get_extremes, pl, plot):
158
+ # Now, we want to filter to only include tracks whose duration falls inside of our selection - we will need to first identify the extremes, then filter based on them
159
+ min_dur, max_dur = get_extremes(
160
+ plot.value, col="duration_seconds", defaults_if_missing=(120, 360)
161
+ ) # Utility function defined in the bottom of the Notebook
162
+ # Calculate how many we are keeping vs throwing away with the filter
163
+ duration_in_range = pl.col("duration_seconds").is_between(min_dur, max_dur)
164
+ print(
165
+ f"Filtering to keep rows between {min_dur}s and {max_dur}s duration - Throwing away {df.select(1 - duration_in_range.mean()).item():.2%} of the rows"
166
+ )
167
+
168
+ # Actually apply the filter
169
+ filtered_duration = df.filter(duration_in_range)
170
+ filtered_duration
171
+ return duration_in_range, filtered_duration, max_dur, min_dur
172
+
173
+
174
+ @app.cell(hide_code=True)
175
+ def _(mo):
176
+ mo.md(
177
+ r"""
178
+ Now that our data is 'clean', let's start coming up with and answering some questions about it. Some examples:
179
+
180
+ - Which tracks or artists are the most popular? (Both globally as well as for each genre)
181
+ - Which genres are the most popular? The loudest?
182
+ - What are some common combinations of different artists?
183
+ - What can we infer anything based on the track's title or artist name?
184
+ - How popular is some specific song you like?
185
+ - How much does the mode and key affect other attributes?
186
+ - Can you classify a song's genre based on its attributes?
187
+
188
+ For brevity, we will not explore all of them - feel free to try some of the others yourself, or go more in deep in the explored ones.
189
+ Make sure to come up with some questions of your own and explore them as well!
190
+ """
191
+ )
192
+ return
193
+
194
+
195
+ @app.cell(hide_code=True)
196
+ def _(filter_genre, filtered_duration, mo, pl):
197
+ most_popular_artists = (
198
+ filtered_duration.lazy()
199
+ # If you saw the Dataset description or looked closely at the Artists column you may notice there are some rows with multiple artists separated by ;;. We will have to separate each of these.
200
+ .with_columns(pl.col("artists").str.split(";"))
201
+ # Similarly to the utility function you saw before, filter_genre is also defined in a later cell.
202
+ # While developing, you can add things out of order then go back to old cells and edit them
203
+ # it's up to you whenever to put them in whichever order makes the most sense to you.
204
+ .filter(True if filter_genre.value is None else pl.col("track_genre").eq(filter_genre.value))
205
+ .explode("artists")
206
+ .group_by("artists")
207
+ .agg(
208
+ # How to aggregate it is also a question,
209
+ # Do we take the sum of each of their songs popularity?
210
+ # Do we just take their most popular song?
211
+ # Do we take an average of their songs popularity?
212
+ # We'll proceed with the average of their top 10 most popular songs for now,
213
+ # but that is something you may want to modify and experiment with, or ask for input from stakeholders in real problems.
214
+ pl.col("popularity").top_k(10).mean(),
215
+ # Say that after doing this you don't recognize them and want to know what are their top hits,
216
+ # Let's also take some of their most popular albums songs for reference:
217
+ pl.col("track_name").sort_by("popularity").unique(maintain_order=True).top_k(5),
218
+ pl.col("album_name").sort_by("popularity").unique(maintain_order=True).top_k(5),
219
+ pl.col("track_genre").top_k_by("popularity", k=1).alias("Most popular genre"),
220
+ # And for good measure, see how many total tracks they have
221
+ pl.col("track_name").n_unique().alias("tracks_count"),
222
+ )
223
+ .sort("popularity", descending=True)
224
+ .collect()
225
+ )
226
+ mo.vstack(
227
+ [
228
+ mo.md("Let's start by taking a look at the most popular artists"),
229
+ # Also adjust the formatting for displaying columns that include multiple values in the same line
230
+ most_popular_artists.with_columns(pl.col(pl.List(pl.String())).list.join("\n")),
231
+ mo.md("Recognize any of your favourite songs? Me neither. Let's try adding a filter by genre"),
232
+ filter_genre,
233
+ mo.md(
234
+ "(the code is omitted for brevity, but you can click the eye icon to see it)",
235
+ ),
236
+ ],
237
+ )
238
+ return (most_popular_artists,)
239
+
240
+
241
+ @app.cell(hide_code=True)
242
+ def _(mo):
243
+ mo.md(
244
+ r"""
245
+ So far so good - but there's been a distinct lack of visualations, so let's fix that.
246
+
247
+ Let's start simple, just some metrics for each genre:
248
+ """
249
+ )
250
+ return
251
+
252
+
253
+ @app.cell
254
+ def _(filtered_duration, pl, px):
255
+ fig_dur_per_genre = px.scatter(
256
+ filtered_duration.group_by("track_genre")
257
+ .agg(
258
+ pl.col("duration_seconds", "popularity").mean().round(2),
259
+ )
260
+ .sort("track_genre", descending=True),
261
+ hover_name="track_genre",
262
+ y="duration_seconds",
263
+ x="popularity",
264
+ )
265
+ fig_dur_per_genre
266
+ return (fig_dur_per_genre,)
267
+
268
+
269
+ @app.cell(hide_code=True)
270
+ def _(mo):
271
+ mo.md(
272
+ r"""
273
+ Now, why don't we play a bit with marimo's UI elements?
274
+
275
+ We will use Dropdowns to allow for the user to select any column to use for the visualisation, and throw in some extras
276
+
277
+ - A slider for the transparency to help understand dense clusters
278
+ - Add a Trendline to the scatterplot (requires statsmodels)
279
+ - Filter by some specific Genre
280
+ """
281
+ )
282
+ return
283
+
284
+
285
+ @app.cell(hide_code=True)
286
+ def _(
287
+ alpha,
288
+ color,
289
+ filter_genre2,
290
+ filtered_duration,
291
+ include_trendline,
292
+ mo,
293
+ pl,
294
+ px,
295
+ x_axis,
296
+ y_axis,
297
+ ):
298
+ fig2 = px.scatter(
299
+ filtered_duration.filter(
300
+ (pl.col("track_genre") == filter_genre2.value) if filter_genre2.value is not None else True
301
+ ),
302
+ x=x_axis.value,
303
+ y=y_axis.value,
304
+ color=color.value,
305
+ opacity=alpha.value,
306
+ trendline="lowess" if include_trendline.value else None,
307
+ render_mode="webgl",
308
+ # strings on hover get fairly heavy when there are too many rows, but you can try using it after applying a few filters
309
+ # hover_name="track_name",
310
+ # hover_data=("artists", "album_name"),
311
+ )
312
+ chart2 = mo.ui.plotly(fig2)
313
+
314
+ mo.vstack([mo.hstack([x_axis, y_axis, color, alpha, include_trendline, filter_genre2]), chart2])
315
+ return chart2, fig2
316
+
317
+
318
+ @app.cell(hide_code=True)
319
+ def _(mo):
320
+ mo.md(
321
+ r"""
322
+ As we have seen before, we can also use the plot as an input to select a region and look at it in more detail.
323
+
324
+ Try selecting a region then performing some explorations of your own with the data inside of it.
325
+ """
326
+ )
327
+ return
328
+
329
+
330
+ @app.cell
331
+ def _(chart2, filtered_duration, mo, pl):
332
+ # Looking at which sort of songs were included in that region
333
+ if len(chart2.value) == 0:
334
+ out = mo.md("No data found in selection")
335
+ active_columns = column_order = None
336
+ else:
337
+ active_columns = list(chart2.value[0].keys())
338
+ column_order = ["track_name", *active_columns, "album_name", "artists"]
339
+ out = filtered_duration.join(pl.DataFrame(chart2.value).unique(), on=active_columns).select(
340
+ pl.col(column_order), pl.exclude(*column_order)
341
+ )
342
+ out
343
+ return active_columns, column_order, out
344
+
345
+
346
+ @app.cell(hide_code=True)
347
+ def _(mo):
348
+ mo.md(
349
+ r"""
350
+ In this notebook, we've focused on a few key aspects. First, it's essential to *understand* the data you're working with — this forms the foundation of any analysis.
351
+
352
+ Creating plots is a powerful way to identify patterns, outliers, and trends. These visualizations are not just for _presentation_; they are tools for deeper insight.
353
+
354
+ /// NOTE
355
+ With marimo's `interactive` UI elements, exploring different _facets_ of the data becomes seamless, allowing for dynamic analysis without altering the code.
356
+
357
+ Keep these points in mind as you continue to work with data.
358
+ """
359
+ )
360
+ return
361
+
362
+
363
+ @app.cell(hide_code=True)
364
+ def _(mo):
365
+ mo.md(r"""# Utility Functions and UI Elements""")
366
+ return
367
+
368
+
369
+ @app.cell
370
+ def get_extremes():
371
+ def get_extremes(selection, col, defaults_if_missing):
372
+ "Get the minimum and maximum values for a given column within the selection"
373
+ if selection is None or len(selection) == 0:
374
+ print(
375
+ f"Could not find a selected region. Using default values {defaults_if_missing} instead, try clicking and dragging in the plot to change them."
376
+ )
377
+ return defaults_if_missing
378
+ else:
379
+ return (
380
+ min(row[col] for row in selection),
381
+ max(row[col] for row in selection),
382
+ )
383
+ return (get_extremes,)
384
+
385
+
386
+ @app.cell
387
+ def _(filtered_duration, mo):
388
+ filter_genre = mo.ui.dropdown(
389
+ options=filtered_duration["track_genre"].unique().sort().to_list(),
390
+ allow_select_none=True,
391
+ value=None,
392
+ searchable=True,
393
+ label="Filter by Track Genre:",
394
+ )
395
+ return (filter_genre,)
396
+
397
+
398
+ @app.cell
399
+ def _(filtered_duration, mo):
400
+ # Columns that make sense for the scatterplot and the corresponding UI elements
401
+ options = [
402
+ "duration_seconds",
403
+ "popularity",
404
+ "danceability",
405
+ "energy",
406
+ "key",
407
+ "loudness",
408
+ "mode",
409
+ "speechiness",
410
+ "acousticness",
411
+ "instrumentalness",
412
+ "liveness",
413
+ "valence",
414
+ "tempo",
415
+ ]
416
+ x_axis = mo.ui.dropdown(options, value="energy", label="X")
417
+ y_axis = mo.ui.dropdown(options, value="danceability", label="Y")
418
+ color = mo.ui.dropdown(options, value="loudness", allow_select_none=True, searchable=True, label="Color column")
419
+ alpha = mo.ui.slider(start=0.01, stop=1.0, step=0.01, value=0.1, label="Alpha", show_value=True)
420
+ include_trendline = mo.ui.checkbox(label="Trendline")
421
+ # We *could* reuse the same filter_genre from above, but it would cause marimo to rerun both the table and the graph whenever we change it
422
+ filter_genre2 = mo.ui.dropdown(
423
+ options=filtered_duration["track_genre"].unique().sort().to_list(),
424
+ allow_select_none=True,
425
+ value=None,
426
+ searchable=True,
427
+ label="Filter by Track Genre:",
428
+ )
429
+ return (
430
+ alpha,
431
+ color,
432
+ filter_genre2,
433
+ include_trendline,
434
+ options,
435
+ x_axis,
436
+ y_axis,
437
+ )
438
+
439
+
440
+ @app.cell(hide_code=True)
441
+ def _(mo):
442
+ mo.md("""# Appendix : Some other examples""")
443
+ return
444
+
445
+
446
+ @app.cell
447
+ def _(mo):
448
+ # Components to filter for some specific song
449
+ filter_artist = mo.ui.text(label="Artist: ")
450
+ filter_track = mo.ui.text(label="Track name: ")
451
+ return filter_artist, filter_track
452
+
453
+
454
+ @app.cell(disabled=True)
455
+ def _(filtered_duration, mo, pl):
456
+ # Note that we cannot use dropdown due to the sheer number of elements being enormous:
457
+ all_artists = filtered_duration.select(pl.col("artists").str.split(";").explode().unique().sort())["artists"].to_list()
458
+ all_tracks = filtered_duration["track_name"].unique().sort().to_list()
459
+ alternative_filter_artist = mo.ui.dropdown(all_artists, value=None, searchable=True)
460
+ alternative_filter_track = mo.ui.dropdown(all_tracks, value=None, searchable=True)
461
+ # So we just provide freeform text boxes and filter ourselfves later
462
+ # (the "alternative_" in the name is just to avoid conflicts with the above cell,
463
+ # despite this being disabled marimo still requires global variables to be unique)
464
+ return (
465
+ all_artists,
466
+ all_tracks,
467
+ alternative_filter_artist,
468
+ alternative_filter_track,
469
+ )
470
+
471
+
472
+ @app.cell
473
+ def _(filter_artist, filter_track, filtered_duration, mo, pl):
474
+ def score_match_text(col: pl.Expr, string: str | None) -> pl.Expr:
475
+ if not string:
476
+ return pl.lit(0)
477
+ col = col.str.to_lowercase()
478
+ string = string.casefold()
479
+ return (
480
+ # For a more professional use case, you might want to look into string distance functions
481
+ # in the polars-ds package or other polars plugins
482
+ -col.str.len_chars().cast(pl.Int32())
483
+ + pl.when(col.str.contains(string)).then(50).otherwise(0)
484
+ + pl.when(col.str.starts_with(string)).then(50).otherwise(0)
485
+ )
486
+
487
+
488
+ filtered_artist_track = (
489
+ filtered_duration.select(
490
+ pl.col("artists"),
491
+ pl.col("track_name"),
492
+ (
493
+ score_match_text(pl.col("track_name"), filter_track.value)
494
+ + pl.col("artists").str.split(";").list.eval(score_match_text(pl.element(), filter_artist.value)).list.sum()
495
+ ).alias("match_score"),
496
+ pl.col("album_name"),
497
+ pl.col("track_genre"),
498
+ pl.col("popularity"),
499
+ pl.col("duration_seconds"),
500
+ )
501
+ .filter(pl.col("match_score") > 0)
502
+ .sort("match_score", descending=True)
503
+ )
504
+
505
+ mo.vstack([mo.md("Filter a track based on its name or artist"), filter_artist, filter_track, filtered_artist_track])
506
+ return filtered_artist_track, score_match_text
507
+
508
+
509
+ @app.cell
510
+ def _(filter_genre2, filtered_duration, mo, pl):
511
+ # Artists combinations
512
+ artist_combinations = (
513
+ filtered_duration.lazy()
514
+ .filter((pl.col("track_genre") == filter_genre2.value) if filter_genre2.value is not None else True)
515
+ .with_columns(pl.col("artists").str.split(";"))
516
+ .with_columns(pl.col("artists").alias("other_artist"))
517
+ .explode("artists")
518
+ .explode("other_artist")
519
+ # Filter to:
520
+ # 1) Remove an artist with themselves
521
+ # 2) Remove duplicate combinations, otherwise we would have once row for (A, B) and one for (B, A)
522
+ .filter(pl.col("artists") > pl.col("other_artist"))
523
+ .group_by("artists", "other_artist")
524
+ .len("count")
525
+ .collect()
526
+ )
527
+ mo.vstack(
528
+ [
529
+ mo.md("Check which artists collaborate with others most often (reuses the last genre filter)"),
530
+ filter_genre2,
531
+ artist_combinations.sort("count", descending=True),
532
+ ],
533
+ align="center",
534
+ )
535
+ return (artist_combinations,)
536
+
537
+
538
+ @app.cell
539
+ def _():
540
+ import marimo as mo
541
+ return (mo,)
542
+
543
+
544
+ @app.cell
545
+ def _():
546
+ import polars as pl
547
+ import plotly.express as px
548
+ return pl, px
549
+
550
+
551
+ if __name__ == "__main__":
552
+ app.run()