- size(800, 600); // Adjusted height to 600
- background(255);
- // Define variables
- float numBars = 10.0;
- int gridSize = 10;
- float sum = 0.0;
- float mean = 0.0; // Adjusted mean value
- float xOrigin = width * 0.1;
- float yOrigin = height * 0.2;
- float xEnd = width * 0.9;
- float yEnd = height * 0.9;
- float yLabelOffset = height * 0.04;
- float xLabelOffset = width * 0.04;
- float titleX = width * 0.5;
- float titleY = height * 0.1;
- float smallOffset = height * 0.03;
- float titleFontSize = width * 0.025;
- color barColor = color(100, 200, 100); // Greenish color
- // Define grid and bar dimensions
- float areaWidth = xEnd - xOrigin;
- float areaHeight = yEnd - yOrigin;
- float gridWidth = areaWidth / gridSize;
- float gridHeight = areaHeight / gridSize;
- float maxBarHeight = yEnd - yOrigin;
- float xValue;
- float barStart = yOrigin;
- float barHeight = maxBarHeight / numBars;
- float barLength;
- // Generate random data for bars
- int[] bars = {5, 7, 2, 9, 4, 8, 3, 6, 10, 1};
- // Add title
- fill(0);
- String title = "Graph Visualization";
- textSize(titleFontSize);
- textAlign(CENTER);
- text(title, titleX, titleY);
- // Draw grid lines
- noFill();
- strokeWeight(1);
- for (float x = xOrigin; x < xEnd; x += gridWidth) {
- for (float y = yOrigin; y < yEnd; y += gridHeight) {
- rect(x, y, gridWidth, gridHeight);
- }
- }
- // Draw x and y axes
- strokeWeight(5);
- strokeCap(ROUND);
- line(xOrigin, yEnd, xEnd, yEnd); // x axis
- line(xOrigin, yOrigin, xOrigin, yEnd); // y axis
- // Add x-axis labels
- for (int i = 0; i <= gridSize; i++) {
- String label = str(i);
- text(label, xOrigin + i * gridWidth, yEnd + xLabelOffset);
- }
- // Draw bars and labels
- strokeWeight(1);
- for (int i = 0; i < numBars; i++) {
- fill(barColor); // Adjusted color
- barLength = (bars[i] * gridWidth) / 2; // Adjusted width of the rectangles
- rect(xOrigin, barStart + (i * barHeight), barLength, barHeight);
- // Add bar value labels
- fill(255);
- String label = str(bars[i]);
- text(label, xOrigin + barLength - smallOffset,
- barStart + (i * barHeight) + (barHeight / 1.5 ));
- }
- // Calculate and draw mean line
- for (int i = 0; i < numBars; i++) {
- sum += bars[i];
- }
- mean = sum / numBars; // Adjusted mean calculation
- stroke(235, 16, 13);
- strokeWeight(3);
- xValue = xOrigin + (mean * gridWidth);
- line(xValue, yOrigin, xValue, yEnd);
- // Add mean value label
- fill(235, 16, 13);
- String meanLabel = "Mean: " + mean;
- textSize(titleFontSize);
- textAlign(CENTER);
- text(meanLabel, xValue, height * 0.18);
- save("Assignment2.png");