File: percentage_of_total.py

package info (click to toggle)
python-altair 4.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 9,972 kB
  • sloc: python: 22,391; makefile: 222; sh: 14
file content (21 lines) | stat: -rw-r--r-- 631 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
Calculating Percentage of Total
-------------------------------
This chart demonstrates how to use a joinaggregate transform to display
data values as a percentage of total.
"""
# category: bar charts
import altair as alt
import pandas as pd

source = pd.DataFrame({'Activity': ['Sleeping', 'Eating', 'TV', 'Work', 'Exercise'],
                           'Time': [8, 2, 4, 8, 2]})

alt.Chart(source).transform_joinaggregate(
    TotalTime='sum(Time)',
).transform_calculate(
    PercentOfTotal="datum.Time / datum.TotalTime"
).mark_bar().encode(
    alt.X('PercentOfTotal:Q', axis=alt.Axis(format='.0%')),
    y='Activity:N'
)