Categories
Chart.js

Chart.js — Bar and Line 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.

Arc Configuration

We can change the arc options for polar area, donut, and pie charts.

The properties are all in the Chart.defaults.global.elements.arc object.

For instance, we can write:

Chart.defaults.global.elements.arc.backgroundColor = 'green';

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

We set the Chart.defaults.global.elements.arc.backgroundColor property to the color of the bar.

And the polar area chart will now have all the slices in green.

Other options include stroke alignment, border color, and border width.

Line Chart

We can create a line chart by setting a few options.

To add a line chart, we create a canvas by writing:

<canvas id="myChart"></canvas>

in the HTML.

Then in the JavaScript code, we 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],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We can set many properties in the datasets entries.

Some of them include:

  • backgrounrColor — background-color for the line chart
  • borderColor — line color
  • borderDash — length and spacing of dashes
  • borderWidth — line width
  • label — dataset label
  • order — drawing order
  • pointStyle — point style.

and many more.

Point and line styles can also be changed with various options.

Stacked Area Chart

We can have multiple line charts that are stacked on top of each other.

To add that, we write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
      label: '# of Apples',
      data: [12, 19, 3],
      borderWidth: 1,
      borderColor: 'red'
    }, {
      label: '# of Oranges',
      data: [20, 13, 5],
      borderWidth: 1,
      borderColor: 'blue'
    }]
  },
  options: {
    scales: {
      yAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We have the stacked property set to true to make the 2 lines stacked on top of each other.

The borderColor are set to distinguish them.

Bar Charts

We can create bar charts to show values as vertical bars.

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: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We can have the backgroundColor to set the background color of the bars.

borderColor sets the border color of the bars.

borderWidth sets the border width.

labels have the x-axis labels.

label has the legend label.

data has the y-coordinate values.

Other options include the bar thickness, percentage of the category filled, and max bar thickness:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      barPercentage: 0.5,
      barThickness: 6,
      maxBarThickness: 8,
      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: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The barPercentage and categoryPercentage appear as follows:

// categoryPercentage: 1.0
// barPercentage: 1.0
Bar:        | 1.0 | 1.0 |
Category:   |    1.0    |
Sample:     |===========|

// categoryPercentage: 1.0
// barPercentage: 0.5
Bar:          |.5|  |.5|
Category:  |      1.0     |
Sample:    |==============|

// categoryPercentage: 0.5
// barPercentage: 1.0
Bar:            |1.||1.|
Category:       |  .5  |
Sample:     |==============|

Conclusion

We can change the arc configuration of some graphs.

Also, we can add bar and line charts with Chart.js.

Categories
Chart.js

Chart.js — Changing Chart 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.

Elements Configuration

Wd can change the global element options with the Chart.defaults.global.elements property.

For example, we can write:

Chart.defaults.global.elements.rectangle.borderWidth = 2;

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.35748, 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: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to set the border width of the bar to 2px.

Point Configuration

There are many options we can change with points.

For instance, we can change the radius, point styler, rotation, background color, and more.

To change them, we change the Chart.defaults.global.elements.point property.

For example, we can write:

Chart.defaults.global.elements.point.backgroundColor = 'green';

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],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We get the Chart.defaults.global.elements.point.backgroundColor property to set the background color of a point.

The point properties are applicable for line, radar, and bubble charts.

Line Configuration

We can also change various options for lines.

They include things like tension, background color, border width, border color, line cap style, and more.

To change it, we can write:

Chart.defaults.global.elements.line.borderColor = 'green';

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],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We have:

Chart.defaults.global.elements.line.borderColor = 'green';

to change the line color to green.

Rectangle Configuration

We can change the rectangle elements that are used to represent the bars in the bar chart.

To do that, we set the properties in the Chart.defaults.global.elements.rectangle property.

Options we can change include background color, border width, border color, and skipping borders on some sides.

For example, we can write:

Chart.defaults.global.elements.rectangle.backgroundColor = 'green';

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.35748, 19, 3],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We set the Chart.defaults.global.elements.rectangle.backgroundColor property to set the bar color.

Conclusion

We can change the global options for various parts of a graph.

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 — Font and Animation 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.

Disable Line Drawing for All Datasets

To disable line drawing for all datasets, we can write:

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

to add the showLines: false option to the options object.

Animations

Chart.js comes with many animation options.

We can change how the animation looks and how long it takes.

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: {
    animation: {
      onProgress(animation) {
        console.log(animation.animationObject.currentStep / animation.animationObject.numSteps);
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We add the animation property with the onProgress callback.

The animation object has animationObject.currentStep property to compute the current step.

And the animationObject.numSteps property has the total number of steps for animation.

Other properties includes the easing with the easing to use.

render is a function that renders the chart.

We can also add an onAnimationProgress property to do something when the chart is being animated.

And the onAnimationComplete property lets us run something when the chart is done animating.

Layout Configuration

We can change various layout options with Chart.js.

One option is the padding.

We can change it with the layout.padding property:

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: {
    layout: {
      padding: {
        left: 10,
        right: 10,
        top: 10,
        bottom: 10
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We padding 10 pixels of padding on all 4 sides.

The legend can also be changed with various options.

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: {
    legend: {
      display: true,
      labels: {
        fontColor: 'rgb(255, 99, 132)'
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to change the legend’s font color with the options.legend.labels.fontColor property.

display: true makes the legend display.

Conclusion

We can change layout and animation options with Chart.js

Categories
Chart.js

Chart.js — Chart Tooltips and Labels

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.

Tooltips

We can change the tooltips with the option.tooltips properties.

They include many options like the colors, radius, width, text direction, alignment, and more.

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.35748, 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: {
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          let label = data.datasets[tooltipItem.datasetIndex].label || '';

          if (label) {
            label += ': ';
          }
          label += Math.round(tooltipItem.yLabel * 100) / 100;
          return label;
        }
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to round the numbers to 2 digits.

We have the tooltipItem.yLabel property with the y-axis value.

Now we’ll see that the Red bar’s tooltip shows a number with 2 decimal digits when we hover on it.

Label Color Callback

We can also change the label color callback.

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.35748, 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: {
    tooltips: {
      callbacks: {
        labelColor(tooltipItem, chart) {
          return {
            borderColor: 'rgb(255, 0, 0)',
            backgroundColor: 'rgb(255, 0, 0)'
          };
        },
        labelTextColor(tooltipItem, chart) {
          return 'lightgray';
        }
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We have the options.tooltips.callbacks property with the labelColor method to return an object with the borderColor and the backgroundColor properties.

borderColor has the border color of the tooltip.

And backgroundColor has the background color of the tooltip.

Also, the labelTextColor is a method that returns the color of the tooltip label text.

The tooltipItem object has many properties.

They include the label property with the label string.

value has the value.

xLabel and yLabel have the x and y label values.

datasetIndex has the index of the dataset that the item comes from.

index has the index of the data item in the dataset.

x and y are the x and y position of the matching point.

External (Custom) Tooltips

We can customize our tooltip with the custom method:

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.35748, 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: {
    tooltips: {
      enabled: false,
      custom(tooltipModel) {
        var tooltipEl = document.getElementById('chartjs-tooltip');
        if (!tooltipEl) {
          tooltipEl = document.createElement('div');
          tooltipEl.id = 'chartjs-tooltip';
          document.body.appendChild(tooltipEl);
        }

        if (tooltipModel.body) {
          tooltipEl.innerHTML = tooltipModel.body[0].lines
        }

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

We create a tooltip element and then set the innerHTML to the body[0].lines property’s value.

Now we should see the label value displayed below the graph.

Conclusion

There are many ways to customize labels of a graph.