Energy Mix in JavaScript
Using ApexCharts with JavaScript
This Energy Mix example uses ApexCharts.js directly in JavaScript, with no wrapper component.
Install it with npm install apexcharts, then mount the chart with new ApexCharts(element, options).render().
// A part-to-whole waffle: a 10x10 grid where every square is 1% of the world's
// electricity, coloured by source. Two illustrative scenarios (a rough "today"
// mix and a cleaner projected mix) toggle via the buttons; because the grid
// keeps each cell in place and only recolours where the category boundary
// moves, you watch the fossil band shrink and the renewables band grow.
// `chart.type: 'waffle'` is an alias for the unit chart's grid layout with
// square cells; `grid.total: 100` largest-remainder-rounds the values to exactly
// 100 cells so the grid always reads as percentages. Shares are illustrative.
// Shared by the vanilla-js/React/Vue builds.
var SOURCES = ['Coal', 'Gas', 'Hydro', 'Nuclear', 'Wind', 'Solar', 'Other']
var SOURCE_COLORS = [
'#374151', // Coal
'#94A3B8', // Gas
'#2563EB', // Hydro
'#E11D48', // Nuclear
'#0D9488', // Wind
'#F59E0B', // Solar
'#CBD5E1', // Other
]
var SCENARIOS = {
today: {
label: 'Today',
caption:
'A rough picture of the mix today: fossil fuels (coal + gas) still fill well over half the grid.',
values: [35, 23, 15, 9, 8, 6, 4],
},
future: {
label: '2035 (projected)',
caption:
'A cleaner projected mix: coal squares recolour to wind and solar as the renewables band grows.',
values: [18, 20, 16, 10, 18, 14, 4],
},
}
var options = {
series: SCENARIOS.today.values,
chart: {
id: 'energyWaffle',
type: 'waffle',
height: 420,
animations: {
enabled: true,
speed: 700,
},
},
labels: SOURCES,
colors: SOURCE_COLORS,
legend: {
position: 'bottom',
},
plotOptions: {
unit: {
grid: {
columns: 10,
total: 100,
},
spacing: 1.25,
},
},
}
var chart = new ApexCharts(document.querySelector('#chart'), options)
chart.render()
// Button-driven scenario switch: each scenario is a chart.updateSeries payload;
// the grid keeps every cell in place and recolours only at the moving category
// boundary. (SOURCES, SOURCE_COLORS and SCENARIOS live in the shared head script.)
var buttons = document.querySelectorAll('#scenario-nav button')
var caption = document.getElementById('caption')
function showScenario(key) {
buttons.forEach(function (b) {
b.classList.toggle('active', b.getAttribute('data-scenario') === key)
})
caption.textContent = SCENARIOS[key].caption
chart.updateSeries(SCENARIOS[key].values)
}
buttons.forEach(function (btn) {
btn.addEventListener('click', function () {
showScenario(btn.getAttribute('data-scenario'))
})
})
caption.textContent = SCENARIOS.today.caption