liveBook · Manning

Transform_calculate()

As explained in Data Storytelling with Altair and AI

transform_calculate() is an Altair chart method that derives and adds fields using expression-based transformations.

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.

How Data Storytelling with Altair and AI covers it

How deep it goes
Explains naming and expression arguments through percentage, coordinate, title, and headline examples without detailing transformation internals.
Examples
Uses fake-news percentages, roadmap label coordinates, and article title and headline labels as concrete calculated fields.
What it assumes
Assumes Python, pandas-loaded data, Altair charts, and familiarity with existing dataset field names.
What you can do after
Apply it via Altair to derive visual measures, position annotations, and generate displayed text from existing fields.
How it connects
Connects calculated fields with Altair encodings, quantitative channels, text marks, and interactive chart selections.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Storytelling with Altair and AI. The section links point to the parts of the book it draws on.