In this snippet we will learn about drawing charts in javascript with the Apex Charts library.
Charts manipulation is a common task in web development for many purposes like displaying statistics about how many users in a website, illustrations graphics, and so on.
In javascript there are many libraries for charts and graphs. From among of these is the Apex Charts library. The Apex charts can draw mostly any type of chart like lines, donut, bar, area, etc.
Apex Chart Installation
Installing via npm
npm install apexcharts --save
Installing via script tag
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
Basic usage:
var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render();
Example: Drawing line chart
<div id="chart"></div> <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <script> var options = { chart: { height: 350, type: "line" }, dataLabels: { enabled: true }, colors: ["#FF1654"], series: [ { name: "Users", data: [100, 350, 430, 700, 1200, 1650, 2030, 2500] } ], stroke: { width: [4, 4] }, xaxis: { categories: [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016] }, yaxis: [ { axisTicks: { show: true }, axisBorder: { show: true, color: "#FF1654" }, labels: { style: { colors: "#FF1654" } }, title: { text: "Users", style: { color: "#FF1654" } } } ], tooltip: { shared: false, intersect: true, x: { show: true } }, legend: { horizontalAlign: "left", offsetX: 40 } }; var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script>
In this code i created an instance of ApexChart(). The ApexChart constructor accepts the html node to mount the chart and an options object. The options argument is very important as we can customize the appearance of the graph using this options, like specifying the type, axis data, coloring, stroke width and so on.
So in this example i specified the type in the type property like so:
chart: { height: 350, type: "line" },
In this case the type is line, there are many types you can pass like area, bar, pie, radar, etc. Also i make the chart height to be 350px with the height property.
Next i specified the data that will be rendered using the series, xaxis and yaxis properties as show:
series: [ { name: "Users", data: [100, 350, 430, 700, 1200, 1650, 2030, 2500] } ], xaxis: { categories: [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016] }, yaxis: [ { axisTicks: { show: true }, axisBorder: { show: true, color: "#FF1654" }, labels: { style: { colors: "#FF1654" } }, title: { text: "Users", style: { color: "#FF1654" } } } ]
In the series data array we add the data that will be rendered, in this example i supposed this is the number of users registered in a website over time. The xaxis property specifies the x axis horizontal line which contains the categories which is this example is the years.
The number of series data array have to match the number of xaxis categories. The yaxis also specifies the vertical left bar of the chart and will show the text “Users” as specified in the title property.
The stroke property is an array which specified the thickness of the line. The colors also is an array and specified the line color.
Other options can be passed also like dataLabels, tooltip, legend, etc. Check the Apex Charts docs to learn about the available options.
Finally using the created instance i invoked the render() method which renders the final graph.
In the rendered chart, the Apex chart gives us the ability to save the chart as an svg, jpg or png image.
Example 2: Drawing Bar Chart
Bar charts is commonly used in many software like MS Excel and displayed as a vertical or horizontal bars of different categories.
In the previous example change the type to be bar:
chart: { height: 350, type: "bar" },
You will see the resulting graph is changed to be vertical bars. Each bar have the same color, however you can display each bar with different color using the plotOptions property:
plotOptions: { bar: { distributed: true } }
You have to remove the colors property so that plotOptions take effect.
To reverse the bars display to be horizontal add the horizontal property to plotOptions like so:
plotOptions: { bar: { distributed: true, horizontal: true } }
Now the bars shown horizontal instead of vertical.
You can explore the other chart type on Apexcharts docs.
Real-time Chart Updating
In addition to graph drawing, Apex chart provides us with some methods for updating charts. This can be handy to update a chart according to particular event like clicking a button, or we can use javascript setInterval() function to update the chart periodically every certain seconds.
- chart.appendSeries(series, animate): Append a new series to the existing one.
- chart.updateSeries(series, animate): Update and override the existing series with a new one.
- chart.updateOptions(newOptions, redraw, animate): Update the chart options. The new options object will be merged with the existing object.
In the previous example let’s imagine that the graph data is retrieved from a Web Service every 2000 ms to update the graph. For the purpose of demonstration i will do this using a for loop to generate the data array using Math.random() inside of setInterval():
setInterval(() => { let data = []; for(var i=0; i<8; i++) { data.push(Math.floor(Math.random() * (5000 - 100 + 1) + 100)); } chart.updateSeries([{ data }], true) }, 2000);
In the setInterval() call i am preparing the data array using a for loop i am filling the data array with random numbers using Math.random() function. I iterate 8 times because the existing series in the previous example contains 8 elements.
Next calling the updateSeries() method on the chart instance passing an array which contains an object data and second argument true to animate the graph. If you run the example again you will see the series updates every 2 seconds.
Integrations on frontend frameworks
Apex Charts can be integrated on the popular frontend frameworks like React, Vue and Angular.
React integration
npm install --save react-apexcharts apexcharts
import React from "react"; import Chart from "react-apexcharts"; function App() { const [graph, setGraph] = useState({ options: { chart: { id: "my-chart" }, xaxis: { categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999] } }, series: [ { name: "series-1", data: [30, 40, 45, 50, 49, 60, 70, 91] } ] } }); return ( <div className="app"> <div className="row"> <div className="chart"> <Chart options={graph.options} series={graph.series} type="bar" width="500" /> </div> </div> </div> ); }
Vue integration
Vue 2
npm install --save apexcharts vue-apexcharts
import VueApexCharts from 'vue-apexcharts' Vue.use(VueApexCharts) Vue.component('apexchart', VueApexCharts)
Vue 3
npm install --save apexcharts npm install --save vue3-apexcharts
import VueApexCharts from "vue3-apexcharts"; const app = createApp(App); app.use(VueApexCharts);
<template> <div> <apexchart width="500" type="bar" :options="options" :series="series"></apexchart> </div> </template>