File: top_k_with_others.py

package info (click to toggle)
python-altair 5.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,952 kB
  • sloc: python: 25,649; sh: 14; makefile: 5
file content (29 lines) | stat: -rw-r--r-- 949 bytes parent folder | download
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
"""
Top-K Plot with Others
----------------------
This example shows how to use aggregate, window, and calculate transfromations
to display the top-k directors by average worldwide gross while grouping the 
remaining directors as 'All Others'.
"""
# category: advanced calculations
import altair as alt
from vega_datasets import data

source = data.movies.url

alt.Chart(source).mark_bar().encode(
    alt.X("aggregate_gross:Q").aggregate("mean").title(None),
    alt.Y("ranked_director:N")
        .sort(op="mean", field="aggregate_gross", order="descending")
        .title(None)
).transform_aggregate(
    aggregate_gross='mean(Worldwide_Gross)',
    groupby=["Director"],
).transform_window(
    rank='row_number()',
    sort=[alt.SortField("aggregate_gross", order="descending")],
).transform_calculate(
    ranked_director="datum.rank < 10 ? datum.Director : 'All Others'"
).properties(
    title="Top Directors by Average Worldwide Gross",
)