Vega Lite
Data Transformation
What is the Fold Transform in Vega-Lite and How Can You Use It?

What is the Fold Transform in Vega-Lite and How Can You Use It?

Imagine you have a dataset in a matrix or cross-tabulation format, and you need to convert it into a format that’s easier to use for data visualization. The fold transform in Vega-Lite can help you do just that!

What Does the Fold Transform Do?

The fold transform takes one or more data fields and "folds" them into two new properties:

  • key: This property holds the name of the original data field.
  • value: This property contains the data from the original field.

This helps in standardizing matrix-like data for easier use in visualizations. Let's dive into an example to make this clearer.

When Should You Use the Fold Transform?

The fold transform is particularly useful when you have data structured like this:

CountryGoldSilver
USA1020
Canada726

And you want to convert it into a more flexible format like this:

CountryKeyValue
USAGold10
USASilver20
CanadaGold7
CanadaSilver26

How to Implement the Fold Transform

To apply the fold transform, you use the fold property in your Vega-Lite specification. Here’s a sneak peek at how you can do it:

{
  "transform": [
    {"fold": ["gold", "silver"]}
  ]
}

Example in Action

Given the input data:

[
  {"country": "USA", "gold": 10, "silver": 20},
  {"country": "Canada", "gold": 7, "silver": 26}
]

By applying the fold transform with {"fold": ["gold", "silver"]}, the output will be:

[
  {"key": "gold", "value": 10, "country": "USA", "gold": 10, "silver": 20},
  {"key": "silver", "value": 20, "country": "USA", "gold": 10, "silver": 20},
  {"key": "gold", "value": 7, "country": "Canada", "gold": 7, "silver": 26},
  {"key": "silver", "value": 26, "country": "Canada", "gold": 7, "silver": 26}
]

FAQ

1. What if my data objects contain array-typed fields?

In that case, you might want to use the flatten transform instead of fold, as fold is designed for a list of known fields.

2. What happens to the original fields after folding?

The original fields remain in the output objects along with the new key and value properties.

3. Can I fold more than two fields at a time?

Absolutely! You can list as many fields as you'd like in the fold array. For example: {"fold": ["field1", "field2", "field3"]}.

Try It Yourself

You can see a live example of the fold transform in action by visiting the following Vega-Lite Example (opens in a new tab).

Feel free to experiment and see how the fold transform can make your data visualization tasks easier and more intuitive!