Color in vega bar charts

I want to give color of the bars by using the 'v' field which consists the hexcode of color.

I gave it using datum.v (mentioned in below code)

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28, "v": "#000000"}, {"a": "B", "b": 55,"v": "#000000"}, {"a": "C", "b": 43, "v": "#CD5C5C"},
      {"a": "D", "b": 91, "v": "#FFA07A"}, {"a": "E", "b": 81, "v": "#FFA07A"}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"},
    "color": {
        "value": "datum.v"
        
      }
  }
}

Output:

image

It didn't work, may I know if there are any other ways through which I can give color of the bars using the hexcode in 'v' field.

This works for me:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28, "v": "#000000"}, {"a": "B", "b": 55,"v": "#000000"}, {"a": "C", "b": 43, "v": "#CD5C5C"},
      {"a": "D", "b": 91, "v": "#FFA07A"}, {"a": "E", "b": 81, "v": "#FFA07A"}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"},
    "color": {
        "field": "v"
      }
  }
}

Hi @flash1293

I want the colors that are used in field 'v' for example #000000 is black, I want A and B bars to be black in color.

Ah, gotcha.

Try this:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A simple bar chart with embedded data.",
  "data": {
    "values": [
      {"a": "A", "b": 28, "v": "#000000"},
      {"a": "B", "b": 55, "v": "#000000"},
      {"a": "C", "b": 43, "v": "#CD5C5C"},
      {"a": "D", "b": 91, "v": "#FFA07A"},
      {"a": "E", "b": 81, "v": "#FFA07A"}
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": {"field": "a", "type": "nominal", "axis": {"labelAngle": 0}},
    "y": {"field": "b", "type": "quantitative"},
    "color": {"field": "v", "type": "nominal", "scale": null}
  }
}

1 Like

Thank you @flash1293

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