How do I get my bar graph to fit in the window?

edited October 2015 in Questions about Code

I am trying to make a bar graph and my data has a very high range. I have 51 data points ranging in numbers from 40,000-75,000. Right now I believe the graph is starting at 0 so obviously it is impossible to see the tops of the bars. I'm not exactly sure how to phrase this, but is it possible to scale down the graph in a way that it fits in the view of the window?

int[] data;

void setup() {
size(900,900);
String[] text = loadStrings("averages.txt");
println(text);
data = int(split(text[0], ","));
}

void draw() {
background(255);
fill(0);
stroke(255);

for(int i = 0; i < data.length; i++) {
int multiplier = 2;
float rectWidth = width / data.length;
float ypos = height - (data[i] * multiplier);
rect((rectWidth * i), ypos, rectWidth, (data[i] * multiplier));
}
}
Tagged:

Answers

  • The multiplier should not be set in your loop, it has to be the same for all of your data-points. So the best way is to calculate it in setup().

    first, you would have to find the maximum of your data-points.

      int max = data[0];
      for (int i = 1; i < data.length; i++) {
        if (data[i] > max) {
          max = data[i];
        }
      }
    

    Then you can calculate the multiplier:

    multiplier = (float)height/max;

  • edited November 2015

    if I understand correctly, and with 40,000-70,000 you mean your data points are starting at 40,000 you can obviously do the same as what benja is doing above to find the min, and subtract this from your data:

    multiplier = height/float(max-min);
    and then:
    float ypos = height - ((data[i] - min)*multiplier);

    Be sure to update your legend (if shown) to start at whatever min is in this case too

Sign In or Register to comment.