Yichus/Shares
Builtin package (resource shares.bosatsu).
This is the complete package source used by this build. The export
list names its public API; definitions below give the types and behavior.
New to the API? Start with Make a data app or Build an API, then use this page to look up a definition.
package Yichus/Shares
from Bosatsu/Predef import Int, List, String, add, cmp_Int, foldl_List, map_List, sub
from Yichus/Num/Float64 import Float64, mulf, divf, int_to_Float64
export (
ScaleKind(),
ShareScale(),
ShareRow(),
share_percent,
row_of_counts
)
exposes Yichus/Num/Float64
# A shares chart draws one bar per category, each split into its shares of
# an ordered scale and adding to 100: survey answers from "very positive" to
# "very negative", or how far sons rose or fell from their fathers' status.
# The form is The Economist's diverging stacked bar chart.
#
# The calculator computes every share and orders the bars; the page draws
# them and computes nothing.
# Ordered: the levels run from least to most, take one hue, light to dark,
# and every bar runs from 0 to 100. Diverging: the levels run from one pole
# to the other and the two halves take opposite hues; with an odd number of
# levels the middle one is neutral grey. Every bar is centred on one shared
# line through its neutral middle (or, with an even number of levels, the
# boundary between its halves), so the bars compare by how far they lean.
enum ScaleKind:
Ordered
Diverging
# The scale's level names, in order: two to five of them. Every row has one
# share per level.
struct ShareScale(levels: List[String], kind: ScaleKind)
# One bar. `pick` names the category to the calculator: clicking a segment
# sets the chart's row input to it and its level input to the segment's
# position on the scale, so the segment's share is an ordinary output with
# its own Why. `shares` are percentages in scale order.
struct ShareRow(label: String, pick: Int, shares: List[Float64])
# `count` as a percentage of `total`. A total of 0 gives 0: a category
# with nothing in it has no share of anything, and the page draws it as a
# bar with no data rather than as 0/0.
def share_percent(count: Int, total: Int) -> Float64:
if cmp_Int(total, 0) matches EQ:
int_to_Float64(0)
else:
mulf(divf(int_to_Float64(count), int_to_Float64(total)), int_to_Float64(100))
def size_of(count: Int) -> Int:
if cmp_Int(count, 0) matches LT: sub(0, count)
else: count
# A bar from counts in scale order: each count's share of their sum. The
# sum is taken over the counts' sizes, so a negative count, which is never
# a count, gives a negative share that the page refuses and names, rather
# than two wrongs making a plausible bar. Counts that are all 0 give a bar
# of 0s, which the page draws as having no data.
def row_of_counts(label: String, pick: Int, counts: List[Int]) -> ShareRow:
total = foldl_List(counts, 0, (sum, count) -> add(sum, size_of(count)))
ShareRow(label, pick, map_List(counts, count -> share_percent(count, total)))