Categories
Chart.js

Chart.js — Time and Radial Axes Options

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Time Axis Scale Bounds

We can change the bounds property to control the scale boundary strategy.

It can either be 'data' or 'ticks' .

'data' makes sure data are fully visible.

'ticks' makes sure ticks are fully visible.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [{
        x: new Date(2020, 1, 1),
        y: 1
      }, {
        t: new Date(2020, 4, 1),
        y: 3
      }, {
        t: new Date(2020, 7, 1),
        y: 5
      }, {
        t: new Date(2020, 10, 1),
        y: 7
      }]
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        bounds: 'data'
      }]
    }
  }
});

to display the ticks according to the available data so that they’re visible.

Ticks Source

The ticks.source property controls the tick generation.

The value can be 'auto' , 'data' or 'labels' .

'auto' generates the optimal ticks based on scale size and time options.

'data' generates ticks from data.

'labels' generate ticks from the user given labels only.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [{
        x: new Date(2020, 1, 1),
        y: 1
      }, {
        t: new Date(2020, 4, 1),
        y: 3
      }, {
        t: new Date(2020, 7, 1),
        y: 5
      }, {
        t: new Date(2020, 10, 1),
        y: 7
      }]
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        ticks: {
          source: 'auto'
        }
      }]
    }
  }
});

to let Chart.js generate the optimal ticks.

Linear Radial Axis

Radial axes are used to specify the radar and polar area chart types.

A linear scale is used to chart numeric data.

Linear interpolation is used to determine where value lies in relation to the center of the axis.

We can change the axis range settings with the ticks.suggestedMin and ticks.suggestedMax properties.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'radar',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scale: {
      ticks: {
        suggestedMin: 50,
        suggestedMax: 100
      }
    }
  }
});

to change the suggested min and max values.

This way, we can change the scale values to be different from the default.

Radial Axis Step Size

We can also change the step size.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'radar',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scale: {
      ticks: {
        max: 60,
        min: 0,
        stepSize: 0.5
      }
    }
  }
});

We set the max and min values for the axes with those properties.

And stepSize changes the tick size for the radial axes.

Conclusion

We can change the time axis to what we want.

Also, we can change the radial axis lines.

Categories
Chart.js

Chart.js — Axis Labels and Instance Methods

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Labeling Axes

The labeling axis tells the viewer what they’re viewing.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          callback(value, index, values) {
            return `$${value}`;
          }
        }
      }]
    }
  }
});

We put a dollar before the number with the callback .

value has the y-axis value.

Styling

We can style an axis with various options.

For instance, we can change the color, border, ticks, and more of the grid lines.

We can do that by changing the gridLines property.

To do that, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        gridLines: {
          color: 'green'
        }
      }]
    }
  }
});

We change the gridLine color to 'green' .

There are also other options like the zero line width, zero line color, border dash, and more.

Tick Configuration

We can also change the tick configuration.

To do this, we can change the ticks property.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          fontColor: 'green'
        }
      }]
    }
  }
});

We change the y-axis ticks with the font color to 'green' to make the y-axis labels green.

Other options include font style, line weight, padding, and more.

There’re also options for minor and major ticks.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 20, 40, 50]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          minor: {
            fontColor: 'green'
          },
          major: {
            fontColor: 'red'
          }
        }
      }]
    }
  }
});

to change the minor and major tick options.

The full list of options is at https://www.chartjs.org/docs/latest/axes/styling.html.

Chart Prototype Methods

Each Chart instance has its own instance methods.

They include:

  • destroy — destroys the chart
  • reset — resets the chart to the state before the initial animation.
  • render(config) — render a config with various options.
  • stop — stop any current animation loop
  • resize — resize a chart’s canvas element
  • clear — clear the chart canvas
  • toBase64Image — returns the base64 encoded string of the chart in its current state
  • generateLegend — returns an HTML string of a legend for the chart
  • getElementAtEvent(e) — get element based on the event object.
  • getElementsAtEvent(e) — get elements based on the event object.
  • getDatasetAtEvent(e) — get element under the went point.
  • getDatasetMeta(index) — get a dataset that matches the current index and returns the metadata.

Conclusion

We can call instance methods on a chart.

Also, the labels can be changed the way we want.

Categories
Chart.js

Chart.js — Titles and Legends

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Legend Item Options

There are many options we can change to configure the legend.

The text has the label text.

fillStyle has the fill style of the legend box.

lineCap is a string with the box border CSS.

lineDash is a number array for the canvas box border.

lineDashOffset has the canvas box border offset.

lineJoin has the canvas context lineJoin property value.

lineWidth has the width of the box border.

strokeStyle has the color of the strokes for the legend.

pointStyle has the point style for the legend box.

rotation has the rotation of the point in degrees.

For example, we can link the display of 2 datasets by writing:

var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
var newLegendClickHandler = function(e, legendItem) {
  var index = legendItem.datasetIndex;
  if (index > 1) {
    defaultLegendClickHandler(e, legendItem);
  } else {
    let ci = this.chart;
    [
      ci.getDatasetMeta(0),
      ci.getDatasetMeta(1)
    ].forEach(function(meta) {
      meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
    });
    ci.update();
  }
};

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      borderWidth: 1
    }, {
      label: '# of Votes',
      data: [10, 19, 3],
      borderWidth: 1
    }]
  },
  options: {
    legend: {
      onClick: newLegendClickHandler
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The else block calls update on both datasets.

If one isn’t hidden as indicated with

meta.hidden === null

Then the other bars will also be shown with:

!ci.data.datasets[index].hidden

And we call ci.update to update the chart.

Then we use this function as the value of the options.legend.onClick property to toggle both bars on and off if we click on the legend.

HTML Legends

We can also add the legendCallback property to render an HTML legend.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    legendCallback(chart) {
      //...
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

Title

We can change the way the chart title is rendered at the top of the chart.

For instance, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Chart Title'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to set the options.title.text property to set the options text.

Conclusion

We can change the title and legend options with a few properties.

Categories
Chart.js

Chart.js — Time Axis

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Step Size

We can change the step size of the linear axis.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [0, 0.5, 1, 1.5, 2]
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          max: 5,
          min: 0,
          stepSize: 0.5
        }
      }]
    }
  }
});

We change the stepSize to 0.5 so that the ticks are in intervals of 0.5.

Time Cartesian Axis

Time Cartesian axis is used to display times and dates.

When the ticks are added, it’ll automatically calculate the most comfortable unit based on the size of the scale.

For example, we can write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg==" crossorigin="anonymous"></script>

<script src='https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js'></script>

<canvas id="myChart" width="400" height="400"></canvas>

to add moment.js before Chart.js.

This way, we can use the library to calculate the tick intervals.

Then we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [{
        x: new Date(2020, 1, 1),
        y: 1
      }, {
        t: new Date(2020, 2, 1),
        y: 10
      }]
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'month'
        }
      }]
    }
  }
});

to add the time and number data with the t and y properties.

And we set the type of the x-axis to 'time' so that we display time.

And time.unit is 'month' so that we display the months.

Display Formats

We can change the display format of the ticks to any format that’s supported by moment.js.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [{
        x: new Date(2020, 1, 1),
        y: 1
      }, {
        t: new Date(2020, 4, 1),
        y: 3
      }, {
        t: new Date(2020, 7, 1),
        y: 5
      }, {
        t: new Date(2020, 10, 1),
        y: 7
      }]
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            quarter: 'MMM YYYY'
          }
        }
      }]
    }
  }
});

to set the format to month and year format for quarters.

Scale Distribution

We can change the scale distribution of the data distribution.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'First dataset',
      data: [{
        x: new Date(2020, 1, 1),
        y: 1
      }, {
        t: new Date(2020, 4, 1),
        y: 3
      }, {
        t: new Date(2020, 7, 1),
        y: 5
      }, {
        t: new Date(2020, 10, 1),
        y: 7
      }]
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        distribution: 'series'
      }]
    }
  }
});

We changed the distribution p[roperty to control the data distribution along the scale.

It can be changed to 'linear' , which spreads data according to their time.

And 'series' spreads data with the same distance from each other.

Conclusion

We can make various changes to the time axis with Chart.js.

Categories
Chart.js

Chart.js — Stacked Bar Chart and Radial Chart

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Stacked Bar Chart

We can create a stacked bar chart with Chart.js.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var stackedBar = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
        ],
        borderWidth: 1
      },
      {
        label: '# of Votes',
        data: [10, 28, 23],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});

to create a stacked bar chart with 2 datasets.

We have the stacked properties within the options property to make them stacked.

Horizontal Bar Chart

We can create a horizontal bar chart by changing the type to 'horizontalBar' .

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var stackedBar = new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});

We just changed the type property and change the bars to display horizontally.

Radar

A radar chart is a way of showing multiple data points and variations between them.

To create one, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'radar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
        label: 'red',
        data: [12, 19, 3],
        backgroundColor: 'red'
      },
      {
        label: 'blue',
        data: [12, 13, 13],
        backgroundColor: 'blue'
      },
      {
        label: 'yellow',
        data: [22, 12, 15],
        backgroundColor: 'yellow'
      }
    ]
  },
});

We have 3 datasets to display in the chart.

And we have labels for each dataset.

backgroundColor has the background color for each shape displayed

We should now see a triangle for the chart datasets.

Also, we can change many other options like border color, border dash, borer width, point radius, point border color, point style, and more.

Line styles like background color, border color, border dash, fill, point hover radius, etc. can also be changed.

Scale Options

We can change the scaling with the scale property.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'radar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
        label: 'red',
        data: [12, 19, 3, 22, 12],
        backgroundColor: 'red'
      },
      {
        label: 'blue',
        data: [12, 13, 13],
        backgroundColor: 'blue'
      },
      {
        label: 'yellow',
        data: [22, 12, 15],
        backgroundColor: 'yellow'
      }
    ]
  },
  options: {
    scales: {
      scale: {
        angleLines: {
          display: false
        },
        ticks: {
          suggestedMin: 50,
          suggestedMax: 100
        }
      }
    }
  }
});

to change the scale of the radar chart. The ticks changes the intervals of the lines in the chart.

angleLines.display makes the angle line display if it’s true .

Conclusion

We can create stacked bar charts and radial charts with Chart.js.