Facebook
From Adjowa Asamoah, 1 Month ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 140
  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. int barWidth = 50;
  5. int maxDataValue;
  6. int barSpacing = 20;
  7. int xOffset, yOffset;
  8.  
  9. void setup() {
  10.   size(800, 600);
  11.   maxDataValue = max(data);
  12.   xOffset = (width - (barWidth + barSpacing) * numBars) / 2;
  13.   yOffset = 50;
  14. }
  15.  
  16. void draw() {
  17.   background(255);
  18.  
  19.   // Drawing the bars
  20.   for (int i = 0; i < numBars; i++) {
  21.     int barHeight = (data[i] * (height - 2 * yOffset)) / maxDataValue;
  22.     int barX = xOffset + i * (barWidth + barSpacing);
  23.     int barY = height - yOffset - barHeight;
  24.     color barColor = getColor(i); // Get color based on index
  25.     fill(barColor);
  26.     rect(barX, barY, barWidth, barHeight);
  27.    
  28.     // Display frequency on top of each bar
  29.     fill(0);
  30.     textAlign(CENTER, CENTER);
  31.     text(data[i], barX + barWidth / 2, barY - 10);
  32.    
  33.     // Display label below each bar
  34.     fill(0);
  35.     text(labels[i], barX + barWidth / 2, height - 10);
  36.   }
  37. }
  38.  
  39. // Function to get color based on index
  40. color getColor(int index) {
  41.   switch (index % 3) {
  42.     case 0:
  43.       return color(255, 0, 0); // Red
  44.     case 1:
  45.       return color(0, 255, 0); // Green
  46.     case 2:
  47.       return color(0, 0, 255); // Blue
  48.     default:
  49.       return color(0); // Black
  50.   }
  51. }
  52.