ApexCharts
ApexCharts
Initialize the chart with JavaScript and configure series, colors, and axes.
Step 1: Install ApexCharts
You can install ApexCharts via yarn or include it directly via CDN.
yarn add apexcharts
Step 2: Include Apexcharts Script
Add a chart container in your HTML and include the local ApexCharts JS file.
<!-- Include ApexCharts JS -->
<script src="../assets/libs/apexcharts/apexcharts.min.js"></script>
Step 3: Add Chart HTML
Add a <div> for the chart in your HTML. Then include the ApexCharts library using your local script:
<!-- Chart container -->
<div id="basicChart" data-colors='["var(--bs-primary)"]' class="apex-charts" dir="ltr"></div>
Step 4: Render Chart with JS
Use the following script to get colors from data-colors and render a basic line chart:
// Get colors array from data-colors attribute
function getChartColorsArray(chartId) {
if (document.getElementById(chartId) !== null) {
var colors = document.getElementById(chartId).getAttribute("data-colors");
colors = JSON.parse(colors);
return colors.map(function (value) {
var newValue = value.replace(" ", "");
if (newValue.startsWith("rgba(var(")) {
var matches = newValue.match(/rgba\\(var\\(([^)]+)\\),([\\d.]+)\\)/);
if (matches) {
var cssVar = matches[1];
var alpha = matches[2];
var rgb = getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim();
return "rgba(" + rgb + "," + alpha + ")";
}
} else {
var val = value.split(',');
if (val.length == 2) {
var rgbaColor = getComputedStyle(document.documentElement).getPropertyValue(val[0]);
rgbaColor = "rgba(" + rgbaColor + "," + val[1] + ")";
return rgbaColor;
} else {
return newValue;
}
}
});
}
}
// Get colors for the chart
var basicChartColors = getChartColorsArray("basicChart");
if (basicChartColors) {
var options = {
chart: {
height: 310,
toolbar: { show: false },
zoom: { enabled: false }
},
series: [
{
name: "Total Sales",
type: "line",
data: [10000, 18500, 9000, 25000, 12000, 14000, 6000, 22000, 12000, 17000, 10000, 18000]
}
],
stroke: {
curve: "smooth",
width: [2]
},
fill: {
type: ["solid"],
gradient: {
shade: "light",
type: "vertical",
shadeIntensity: 0.5,
gradientToColors: [basicChartColors[1]],
inverseColors: true,
opacityFrom: 0.2,
opacityTo: 0,
stops: [0, 100]
}
},
colors: [basicChartColors[0], basicChartColors[1]],
xaxis: {
categories: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
},
yaxis: {
min: 0,
labels: { formatter: val => (val / 1000) + "k" }
},
markers: { size: 0 },
tooltip: {
shared: true,
intersect: false,
y: { formatter: val => (val / 1000) + "k" }
},
grid: {
borderColor: "#f1f1f1",
row: { opacity: 0 },
strokeDashArray: 4,
padding: { top: -15, bottom: -3 }
},
legend: { show: false }
};
var basicChart = new ApexCharts(document.querySelector("#basicChart"), options);
basicChart.render();
}
For more chart types and options, visit the ApexCharts documentation.