ColdFusion Quickie - Adding an average to a line chart

This post is more than 2 years old.

This came up in an IM conversation earlier today. Given a simple line chart, is it easy to add an average? Here is a quick way to do it. First, I'll start off with an array of data points. A query would work fine as well of course.

<cfset data = [ ["Apples", 50], ["Bananas", 40], ["Cherries", 72], ["Donuts", 59], ["Beers", 91] ]>

Now let's render the data as a series:

<cfchart chartheight="500" chartwidth="500" title="Test Chart"> <cfchartseries type="line" seriesLabel="Sales"> <cfloop index="datum" array="#data#"> <cfchartdata item="#datum[1]#" value="#datum[2]#"> </cfloop> </cfchartseries> </cfchart>

Which gives us:

Ok - easy enough. Now let's an add an average. I'm simply going to use a second series for the average. I need to do two things. One - I need to get an average. Since I'm looping over my data points I'll just do some basic math in the first loop. Secondly - I need to output a value for each unit from the first series. The value will be the same - the average - but the item will match up with the items in the first series. Here is the complete code sample.

<cfset data = [ ["Apples", 50], ["Bananas", 40], ["Cherries", 72], ["Donuts", 59], ["Beers", 91] ]>

<cfchart chartheight="500" chartwidth="500" title="Test Chart"> <cfchartseries type="line" seriesLabel="Sales"> <cfset total = 0> <cfloop index="datum" array="#data#"> <cfchartdata item="#datum[1]#" value="#datum[2]#"> <cfset total+= datum[2]> </cfloop> </cfchartseries> <cfchartseries type="line" seriesLabel="Average Sales"> <cfset avg = total/arrayLen(data)> <cfloop index="datum" array="#data#"> <cfchartdata item="#datum[1]#" value="#avg#"> </cfloop> </cfchartseries> </cfchart>

Obviously this could be done a bit cleaner, but you get the idea. Here is the result:

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Lina Haddad posted on 9/26/2011 at 10:49 PM

do you have ready function in cfchart that allow us to get the avg of another line?

Comment 2 by Raymond Camden posted on 9/26/2011 at 10:52 PM

I'm sorry - what?

Comment 3 by Lina Haddad posted on 9/27/2011 at 12:31 AM

sorry for confusing , but what i mean is, let's say my chart is showing 12 points (one for each month with different money value) ,is there any ready function in cfchart will draw me the average line for the existing line chart?thank you.

Comment 4 by Raymond Camden posted on 9/27/2011 at 1:22 AM

Well, the whole point of this blog entry was that I had to make the line myself. So...if there _is_ such a function, I don't know. :)