Sunday, February 13, 2011

How can I automatically calculate axis scale and intervals?

Does anyone know where I can find an algorithm that given a set of values (dates) for an axis I can calculate a reasonable scale and tick interval?

  • The tick interval is going to be dependent on your display area. You'll need to take the width of your graph (I'm assuming time is on the X axis) and the width of a date string in your selected font into account in order to come up with a good scale.

    The basic algorithm will go something like this.

    • Scan the list of dates to find the minimum and maximum values.
    • Divide the graph width by the date string width (this can be done once with the result stored in a variable if *both* widths are constant). This step will be easier if you use a fixed-width font and a MM-DD-YYYY date format. If you use a variable-width font and a date format where you spell out the name of the month, you'll need to add extra padding to the string to make sure each date string is the same width. Note that I said *extra* padding. Even if you use a fixed date format, you'll want to pad it with at least one space to avoid crowding. I'll call this value `ticks` because it's exactly how many ticks on your axis will fit based on the width of your graph.
    • Calculate how many days are between your minimum and maximum dates (inclusive). How you do this will depend on what language you're using. Hopefully you have good Date and Calendar implementations to fall back on. I'll just call this value `days`.
    • Calculate the tick interval with the formula `interval = days / (ticks - 1)`.
    • Determine which days fall on tick intervals by adding `interval` to your minimum date until you reach your maximum date. Again, this will depend on what language you use.
  • I've been using the jQuery flot graph library. It's open source and does axis/tick generation quite well. I'd suggest looking at it's code and pinching some ideas from there.

    From Tom

0 comments:

Post a Comment