Skip to main content
Version: 1.0.0

Adding a Reference Line

Create a Bar Chart

First let's create a bar chart using layers api.

To create a simple bar chart, we have the following configuration:

HTML

<div id="chart"></div>

JS

const { muze, getDataFromSearchQuery, env } = viz;
const data = getDataFromSearchQuery();

const RowField = "Horsepower"; 
const ColumnField = "Year";    

const canvas = muze
  .canvas()
  .data(data)
  .rows([RowField])
  .columns([ColumnField])
  .layers([
    {
      mark: "bar",
    },
  ]);

The bar chart looks like this:

Add a reference line using layer

Now we add a reference line showing average for all years by adding a tick layer.

Let's create the definition of the tick layer. Specify the mark type and ecodings of the layer as below:

{
  mark: "tick",
  encoding: {
    x: {
      field: null // Here we are plotting a horizontal reference line. Only
      // the y value changes, so we set x field as null.
    },
    y: RowField, 
    color: {
      value: () => "#f71616"
    }
  }
}

Finally, we create a function which applies aggregation on the data and pass it in source property

  .transform({
    averageLine: function averageLine(dt) {
      return dt.groupBy(
        [],
        [
          {
            aggn: muze.DataModel.AggregationFunctions.AVG,
            field: RowField, 
          },
        ],
      );
    },
  })

As we had defined defAggFn as avg , so average function will be applied on this aggregation.

Complete code

const { muze, getDataFromSearchQuery, env } = viz;
const data = getDataFromSearchQuery();

const RowField = "Horsepower"; 
const ColumnField = "Year";    

const canvas = muze
  .canvas()
  .data(data)
  .rows([RowField])
  .columns([ColumnField])
  .transform({
    averageLine: function averageLine(dt) {
      return dt.groupBy(
        [],
        [
          {
            aggn: muze.DataModel.AggregationFunctions.AVG,
            field: RowField, 
          },
        ],
      );
    },
  })
  .layers([
    {
      mark: "bar",
    },
    {
      mark: "tick",
      name: "averageLine",
      className: "averageLine",
      encoding: {
        x: {
          field: null,
        },
        y: RowField, 
        color: {
          value: () => "#f71616",
        },
      },
      calculateDomain: false,
      source: "averageLine",
      interactive: false,
    },
  ])
  .mount("#chart");

The output looks like this:

Adding reference line in crosstab

For adding this reference line in a crosstab, we just need to add a facet dimension to the rows in our previous code.

...
 canvas.rows(["Cylinders", "Horsepower"])
...

The output looks like this: