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.

Categories
Chart.js

Chart.js — Scatter Chart and Fill Background

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.

Scatter Chart

We can create a scatter chart with Chart.js

It’s a line chart with the x-axis changed to a linear axis.

For example, we can create one by writing:

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'scatter',
  data: {
    datasets: [{
      label: 'Scatter Dataset',
      backgroundColor: 'green',
      data: [{
        x: -10,
        y: 0
      }, {
        x: 0,
        y: 10
      }, {
        x: 10,
        y: 5
      }]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom'
      }]
    }
  }
});

We have the data property with an array of objects with the x and y properties.

x has the x coordinate, and y has the y coordinate on the chart.

The other properties are the same as the line chart.

We can get the options by going to https://www.chartjs.org/docs/latest/charts/line.html#dataset-properties.

Area Charts

Line and radar charts support the fill option instead of the dataset object which can be used to create an area between 2 datasets and the boundary.

We can add the fill with the fill property.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      borderColor: 'green',
      fill: false,
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to disable the fill with the fill property set to false .

Also, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
        label: '# of foo',
        data: [12, 19, 3],
        borderColor: 'green',
        fill: '+2',
        borderWidth: 1
      },
      {
        label: '# of bar',
        data: [1, 4, 3],
        borderColor: 'red',
        fill: false,
        borderWidth: 1
      },
      {
        label: '# of baz',
        data: [2, 9, 13],
        borderColor: 'blue',
        fill: false,
        borderWidth: 1
      }

]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to add fill between dataset 1 and dataset 3 with the '+2' option.

We’ll see the fill between the green and blue line.

The line color is set with the borderWidth property.

We can also set it to a negative number to make the fill between a later dataset and a dataset that’s added earlier.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
        label: '# of foo',
        data: [12, 19, 3],
        borderColor: 'green',
        fill: false,
        borderWidth: 1
      },
      {
        label: '# of bar',
        data: [1, 4, 3],
        borderColor: 'red',
        fill: false,
        borderWidth: 1
      },
      {
        label: '# of baz',
        data: [2, 9, 13],
        borderColor: 'blue',
        fill: '-2',
        borderWidth: 1
      }

]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We can also set fill to 'origin' to make the fill to the origin.

There’s also the propagate option that makes the fill area recursively extends to the visible target defined by the fill value of hidden dataset targets:

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
        label: '# of foo',
        data: [12, 19, 3],
        borderColor: 'green',
        fill: false,
        borderWidth: 1
      },
      {
        label: '# of bar',
        data: [1, 4, 3],
        borderColor: 'red',
        fill: false,
        borderWidth: 1
      },
      {
        label: '# of baz',
        data: [2, 9, 13],
        borderColor: 'blue',
        fill: '-2',
        borderWidth: 1
      }

]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    plugins: {
      filler: {
        propagate: true
      }
    }
  }
});

This way, if a dataset is hidden, then the fill will propagate to the nearest dataset that’s displayed.

Conclusion

We can create scatter charts and line charts will a fill background with Chart.js

Categories
Chart.js

Chart.js — Mixed Chart Types and 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.

Mixed Chart Types

We can have multiple chart types in one chart with Chart.js.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    datasets: [{
      label: 'Bar Dataset',
      data: [10, 20, 30, 40],
      backgroundColor: 'green'
    }, {
      label: 'Line Dataset',
      data: [50, 50, 50, 50],
      type: 'line',
      borderColor: 'blue'
    }],
    labels: ['January', 'February', 'March', 'April']
  },
});

We set the type to the 'line' so that we have one line chart and one bar chart within the same chart.

Drawing Order

The order that they’re drawn can also be changed.

The dataset are drawn so that the first one is topmost.

We can change that by setting the order property:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    datasets: [{
      label: 'Bar Dataset',
      data: [10, 20, 30, 40],
      backgroundColor: 'green',
      order: 2
    }, {
      label: 'Line Dataset',
      data: [20, 20, 20, 20],
      type: 'line',
      borderColor: 'blue',
      order: 1
    }],
    labels: ['January', 'February', 'March', 'April']
  },
});

Cartesian Axes

Cartesian axes are used by line, bar, and bubble charts.

4 cartesian axes are included in Chart.js by default.

They are linear, logarithmic, category, and time.

Axis ID

We can set the axis ID to set the ID of the axis.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'Line 1',
      data: [10, 20, 30, 40],
      backgroundColor: 'green',
      yAxisID: 'first-y-axis'
    }, {
      label: 'Line 2',
      data: [20, 20, 20, 20],
      backgroundColor: 'blue',
      yAxisID: 'second-y-axis'
    }],
    labels: ['January', 'February', 'March', 'April']
  },
  options: {
    scales: {
      yAxes: [{
        id: 'first-y-axis',
        type: 'linear'
      }, {
        id: 'second-y-axis',
        type: 'linear'
      }]
    }
  }
});

We set the id of the axes in the options object to set the axes to display.

Category Cartesian Axis

We can change the category cartesian axis.

We can change the minimum and maximum items to display.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      data: [10, 20, 30, 40, 50, 60]
    }],
    labels: ['January', 'February', 'March', 'April', 'May', 'June']
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          min: 'March'
        }
      }]
    }
  }
});

Then the leftmost item is 'March' and 'January' and 'February' aren’t displayed.

Linear Cartesian Axis

We can change settings in the linear cartesian axis, which is the axis for displaying numerical data.

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: {
          suggestedMin: 50,
          suggestedMax: 100
        }
      }]
    }
  }
});

We set the suggestedMin and suggestedMax properties to set the min and max values and it’s adjusted to fit the values.

If we have values in the dataset below 50 or higher than 100, then they’ll still be displayed.

Conclusion

We can set various options for the axes with Chart.js.

Categories
Chart.js

Chart.js — Doughnut/Pie, Polar Area, and Bubble Charts

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.

Doughnut and Pie Charts

We can create a doughnut chart with the type set to 'doughnut' .

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      backgroundColor: ['red', 'blue', 'yellow'],
      data: [10, 20, 30]
    }]
  },
});

to create a doughnut chart with 3 colors.

The data is an array of numbers.

Dataset properties includes backgroundColor to change the background color.

borderAlign changes the alignment of the border.

borderColor changes the border color.

borderWidth changes the border width.

hoverBackgroundColor changes the color when we hover over the segments.

hoverBorder changes the segment’s color when we hover on it.

weight changes the weight.

The full list of options are at https://www.chartjs.org/docs/latest/charts/doughnut.html.

Polar Area

A polar area chart is similar to pie charts, but each segment has the same angle.

The radius of the segment is different according to the value.

To create one, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'polarArea',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      backgroundColor: ['red', 'blue', 'yellow'],
      data: [10, 20, 30]
    }]
  },
});

We created a polar area chart with the type set to 'polarArea' .

Everything else is the same as the doughnut chart.

We can change the border alignment with the borderAlign property.

If it’s 'center' , then the border of the arcs will overlap.

If it’s 'inner' , then it’s guaranteed that the borders won’t overlap.

We can change the polar area chart’s global default options with the Chart.defaults.polarArea property.

The full list of options are at https://www.chartjs.org/docs/latest/charts/polar.html.

Bubble Chart

A bubble chart is used to display 3 dimensions of data at the same time.

The location of the bubble is determined by the first 2 dimensions and the corresponding x and y axes.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'bubble',
  data: {
    datasets: [{
        label: 'John',
        data: [{
          x: 3,
          y: 7,
          r: 10
        }],
        backgroundColor: "green",
        hoverBackgroundColor: "green"
      },
      {
        label: 'Paul',
        data: [{
          x: 6,
          y: 2,
          r: 10
        }],
        backgroundColor: "green",
        hoverBackgroundColor: "green"
      },
      {
        label: 'George',
        data: [{
          x: 2,
          y: 6,
          r: 10
        }],
        backgroundColor: "green",
        hoverBackgroundColor: "green"
      },
    ]
  }
});

We have an array with the datasets property.

Each entry has the data property with an object with the x , y and r properties.

x and y are the x coordinates.

And r is the radius of the bubble in pixels.

r isn’t scaled by the chart. It’s the eaw radius in pixels of the bubble drawn in the canvas.

We can change many other options like the border, background, hover background color, hover radius, label, and more.

The full list of options are at https://www.chartjs.org/docs/latest/charts/bubble.html

Conclusion

We can create doughnut, pie, polar area, and bubble charts with Chart.js