Search code examples
jsonvisualizationvega-lite

Color gradient for bars in simple bar chart and ordinal catagories


I simply cannot seem to change the colors of a bar chart over ordinal categories. I was able to give every bar a different color by setting the color encoding with a ordinal type. However it defaults to the blues color scheme. I want the range of colors to be different. Let's say from #FFFFFF to #000000. I could not discover how to provide my own such colors on which the color gradient will be based. Anyone got a clue?

This is what I tried:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28}, {"a": "B", "b": 55}, {"a": "C", "b": 43},
      {"a": "D", "b": 91}, {"a": "E", "b": 81}, {"a": "F", "b": 53},
      {"a": "G", "b": 19}, {"a": "H", "b": 87}, {"a": "I", "b": 52}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"},
    "color": {"field": "a", "type": "ordinal"}
  }
}

And this is how it looks like: Example bar chart

As you can see, it simply gives a blue color range. How do I provide my own?


Solution

  • enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "description": "A simple bar chart with embedded data.",
      "data": {
        "values": [
          {"a": "A", "b": 28}, {"a": "B", "b": 55}, {"a": "C", "b": 43},
          {"a": "D", "b": 91}, {"a": "E", "b": 81}, {"a": "F", "b": 53},
          {"a": "G", "b": 19}, {"a": "H", "b": 87}, {"a": "I", "b": 52}
        ]
      },
      "mark": "bar",
      "encoding": {
        "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
        "y": {"field": "b", "type": "quantitative"},
        "color": {"field": "a", "type": "ordinal" ,"scale":{"scheme":["blue", "red"], "interpolate":"cubehelix"}}
      }
    }