transform_calculate() derives a field from existing data with an expression and makes the result available to an Altair chart. It turns raw columns into a directly visualized measure, such as the percentage of fake articles. section 5.5
Use the method progressively:
- Name the derived field as the first argument, such as 'Percentage of Fake Articles'. section 5.5
- Supply an expression as the second argument, using datum fields such as Number of Fake Articles and Number of Articles. section 5.5
Calculate fake-news percentages
A dataset contains fake-article counts and total-article counts for each category. Add the percentage directly in the chart specification, then encode it on the y axis: transform_calculate('Percentage of Fake Articles', alt.datum['Number of Fake Articles'] / alt.datum['Number of Articles'] * 100). The resulting chart compares categories by their proportion of fake articles rather than by raw article totals. section 5.5
Position labels in a roadmap
For rectangle annotations, calculate a midpoint field with transform_calculate(y_half='datum.y2/2') and encode y_half for the text mark. The derived coordinate centers each label vertically without requiring a manually entered position.
