xxxxxxxxxx
111
// Initialising variables
let data;
let selectedEnergy = 'Solar';
let xValues = [];
let yValues = [];
let maxEnergyValue = 0;
// let backgroundImage;
// Loading the data
function preload() {
// backgroundImage = loadImage('bg.png');
data = loadTable('energy.csv', 'csv', 'header');
}
function setup() {
createCanvas(700, 800);
// Set up interactive controls
let energySelector = createSelect();
energySelector.position(20, 20);
energySelector.option('Solar');
energySelector.option('Wind');
energySelector.option('Hydropower');
energySelector.option('TraditionalBiomass ');
energySelector.option('OtherRenewables');
energySelector.option('Biofuels');
energySelector.option('Coal');
energySelector.option('Nuclear');
energySelector.option('Gas');
energySelector.option('Oil');
energySelector.changed(updateEnergy);
processData();
}
function draw() {
background(255);
// image(backgroundImage, 0, 0, width, height);
// Drawing the line graph
drawLineGraph();
}
// Update the selected energy type
function updateEnergy() {
selectedEnergy = this.value();
// Reprocess data when energy type changes
processData();
}
function processData() {
// Extract x and y values from the data for the selected energy type
xValues = [];
yValues = [];
// extracting information from the table
for (let i = 0; i < data.getRowCount(); i++) {
let year = data.getNum(i, 'Year');
let value = data.getNum(i, selectedEnergy);
xValues.push(year);
yValues.push(value);
}}
function drawLineGraph() {
// Drawing the axes
// fill('black');
stroke(0);
strokeWeight(1);
line(100, height - 100, width - 100, height - 100);
line(100, height - 100, 100, 100);
// Drawing the title
textSize(25);
textStyle(BOLD);
textAlign(CENTER, CENTER);
text(selectedEnergy + ' Energy Usage Over Time', width / 2, 50);
//calculating y-axis maximum value for scaling
let maxYValue = max(yValues);
// Draw the data points
noFill();
beginShape();
for (let i = 0; i < xValues.length; i++) {
let x = map(xValues[i], min(xValues), max(xValues), 100, width - 100);
let y = map(yValues[i], 0, maxYValue, height - 100, 100);
// Drawing data points
vertex(x, y);
ellipse(x, y, 8, 8);
}
endShape();
// Draw x-axis labels for years
textAlign(CENTER);
// Calculate the spacing between labels
let xStep = (width - 200) / (xValues.length - 1);
for (let i = 0; i < xValues.length; i+=10) {
let x = 100 + i * xStep;
text(xValues[i], x, height - 70);
}
// Drawing y-axis labels for amounts
textAlign(RIGHT, CENTER);
let yStep = maxYValue / 10;
// Calculate the spacing between labels based on the maximum value
for (let i = 0; i <= maxYValue; i += yStep) {
let y = map(i, 0, maxYValue, height - 100, 100);
text(nf(i, 0, 2), 90, y);
}
}