PaulG
PaulG

Reputation: 286

How can I filter values based on other columns?

How can I select certain values and/or values conditional on other columns in vega-lite? For example, below I only want to show values that have "red" in the column "c".

{
  "data": {
    "values": [
      {"a": "A", "b": 2, "c": "red"}, 
      {"a": "A", "b": 7, "c": "red"}, 
      {"a": "A", "b": 4, "c": "blue"},
      {"a": "B", "b": 1, "c": "blue"}, 
      {"a": "B", "b": 2, "c": "red"} 
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal"},
    "y": {"aggregate": "average", "field": "b", "type": "quantitative"}
  }
}

I have tried adding the following code before "mark": "bar", according to this vega github tutorial, and using the online vega editor, but it doesn't filter column b. I thought I could use it to somehow filter a string as well.

"transform": {
    "filter": "datum.b > 3"
  },

Follow-up question regarding multiple filtering criteria.

Upvotes: 1

Views: 593

Answers (1)

jakevdp
jakevdp

Reputation: 86330

You can do this with a filter transform:

{
  "data": {
    "values": [
      {"a": "A", "b": 2, "c": "red"},
      {"a": "A", "b": 7, "c": "red"},
      {"a": "A", "b": 4, "c": "blue"},
      {"a": "B", "b": 1, "c": "blue"},
      {"a": "B", "b": 2, "c": "red"}
    ]
  },
  "transform": [{"filter": "datum.c == 'red'"}],
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal"},
    "y": {"aggregate": "average", "field": "b", "type": "quantitative"}
  }
}

Upvotes: 2

Related Questions