As mentioned in the data transformations documentation of altair, in most cases, it is suggested to perform transformations outside the chart definition, so in our case using R. Of course, data transforms inside the chart can also be useful in some cases. So far, we have been filtering the data in R and then using the modified data in the chart specification. Now, we use the transform_filter() to subset the data inside the chart. Here is the filter transfrom documentation. We make the linechart we have seen in a previous section using the code below:

chart_disasters = alt$Chart("https://raw.githubusercontent.com/vega/vega-datasets/master/data/disasters.csv")$
  mark_line()$
  encode(
    x = 'Year:Q',
    y = 'Deaths:Q',
    tooltip = c("Year", "Deaths")
  )$
  properties(
    height = 300,
    width = 600
  )$
  transform_filter(
   alt$FieldEqualPredicate(field = "Entity", equal = "All natural disasters")
  )


We use the field predicates to assess whether a data point satisfied certain conditions. As mentioned in the field predicates reference the FieldEqualPredicate evaluates whether a field is equal to a particular value. The variable is the first argument and the condition is the second argument. Go through the field predicates altair documentation and vega-lite documentation and use the FieldOneOfPredicate for the exercise below.

Exercise - Use the filter transform to obtain the data related to volcanic activity and earthquake and make an area chart like the one below.


We now also use the transform_window() for data transformation to compute and plot a windowed aggregation of the deaths over all available years. Here is the window transform documentation.

chart_disasters = alt$Chart("https://raw.githubusercontent.com/vega/vega-datasets/master/data/disasters.csv")$
  transform_window(
    cumulative_count='sum(Deaths)'
  )$
  mark_area()$
  encode(
    x = 'Year:O',
    y = 'cumulative_count:Q',
    tooltip = c("Year:Q", 'cumulative_count:Q')
  )$transform_filter(
    alt$FieldEqualPredicate(field = "Entity", equal = "All natural disasters")
  )$
  properties(
    height = 300,
    width = 600
  )