Facebook
From Adjowa Asamoah, 1 Month ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 145
  1. int[] data = {120, 200, 300, 150, 250}; // Data representing the height of each bar
  2. String[] labels = {"A", "B", "C", "D", "E"}; // Labels for each bar
  3. int numBars = data.length;
  4. float barWidthPercent = 0.1; // Percentage of canvas width occupied by each bar
  5. float maxDataValue;
  6. float barSpacingPercent = 0.02; // Percentage of canvas width for spacing between bars
  7. float xOffsetPercent = 0.1; // Percentage of canvas width for x offset
  8. float yOffsetPercent = 0.1; // Percentage of canvas height for y offset
  9.  
  10. void setup() {
  11.   size(300, 300);
  12.   maxDataValue = max(data);
  13. }
  14.  
  15. void draw() {
  16.   background(255);
  17.  
  18.   // Calculate dimensions based on canvas size
  19.   float canvasWidth = width * (1 - 2 * xOffsetPercent);
  20.   float canvasHeight = height * (1 - 2 * yOffsetPercent);
  21.   float barWidth = canvasWidth * barWidthPercent;
  22.   float barSpacing = canvasWidth * barSpacingPercent;
  23.   float xOffset = width * xOffsetPercent;
  24.   float yOffset = height * yOffsetPercent;
  25.  
  26.   // Drawing the bars
  27.   for (int i = 0; i < numBars; i++) {
  28.     float barHeight = (data[i] * canvasHeight) / maxDataValue;
  29.     float barX = xOffset + i * (barWidth + barSpacing);
  30.     float barY = height - yOffset - barHeight;
  31.     color barColor = getColor(i); // Get color based on index
  32.     fill(barColor);
  33.     rect(barX, barY, barWidth, barHeight);
  34.    
  35.     // Display frequency on top of each bar
  36.     fill(0);
  37.     textAlign(CENTER, CENTER);
  38.     text(data[i], barX + barWidth / 2, barY - 10);
  39.    
  40.     // Display label below each bar
  41.     fill(0);
  42.     text(labels[i], barX + barWidth / 2, height - 10);
  43.   }
  44. }
  45.  
  46. // Function to get color based on index
  47. color getColor(int index) {
  48.   int shade = int(map(index, 0, numBars - 1, 0, 255)); // Map index to a shade of grey and cast to int
  49.   return color(shade);
  50. }
  51.