How to set variables and iterate using Vega

Just a disclaimer: I'm new to Vega, so chances are this is a dumb question. Please let me know if I'm on the wrong path :slightly_smiling_face:

At any rate, the context is that I'm trying create a 3x4 grid of text fields as part of a visualiation, each of which has its own action when you click the field. The problem is 95% of the code is redundant between marks, so I'm trying to figure out a way to clean it up. What I would like accomplish do is something like this:

//JavaScript style variable definitions
let obj = [
  {suffix: "one"},
  {suffix: "two"},
  {suffix: "three"}
];
let prefix = "www.abc.com/";
let spacingX = 20;

//awkward merging of JavaScript and Vega to create marks
for(let i=0; i<obj.length; i++){
  mark{
    ...
   encode{
      ...
        x: { value: i * spacingX },
        href: { value: prefix + obj[i].suffix },
      ...
  }
   ...
  }
}

I realize that there's no such thing as a "for loop" in Vega's JSON looking config file, but I was wondering whether you could mimic that functionality somehow. And if you get too caught up on the concept of putting this kind of code in Vega, let me ask this: how would you create a 3x4 grid of text nodes with slightly different hrefs and a ton of redundant code? Would you just accept that there's a ton of redundant code and enter each mark while manually entering the x/y coordinates, or would you have a way to make it a little more easy to edit if you learned you want a little more spacing between each node?

Just to answer one of my two questions, I learned at least a way to set variables. First, you set the signal:

signals [
  { name: "spacing", value: 10 },
  { name: "prefix", value: "www.abc.com/" }
]

Then you can implement them as such:

mark{
  ...
  encode{
    ...
    y: { signal: "spacing * 2" }, //start y position for third row
    href: { signal: "prefix + 'stuff'" },
  ...
}

Not posting in here because I know the answer, just that you may be able to get better support on the Vega spec by posting an issue on the associated GitHub project: https://github.com/vega/vega

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.