Interesting CFCHART Trick

A reader, Asaf, and I exchanged a few emails earlier this week about an interesting little cfchart trick. It relates to a blog entry I did earlier in the month: Ask a Jedi: Showing the Values on a Chart. Specifically - controlling the labels on your chart. I definitely recommend reading that article first as some of the following won’t make sense without it. Asaf discovered that when you specify a dataLabel style in your chart XML, one of the special values is $(desc). In my last article I showed a few other tokens (value, colPercent, colTotal). The desc token is interesting. It takes a string from your data and uses it for the label. So consider this hacked up data:

<cfset q2 = queryNew("year,employees","integer,varchar")> <!--- generate random sales data ---> <cfloop index="y" from="1994" to="1998"> <cfscript> queryAddRow(q2); querySetCell(q2, "year", y); querySetCell(q2, "employees", randRange(2,8) & " foo #y#"); </cfscript> </cfloop>

Previously, this query was simply a set of years and employees. Notice I still use a random number for that. But now I’ve added a string, foo #y#, after the value. So one row of the query may look like so:

year=1994 employes=5 foo 1994

In the style XML for the chart, I used:

<?xml version="1.0" encoding="UTF-8"?> <frameChart is3D="false"> <legend useMarkers="true"/> <elements action="" place="Default" outline="black"> <series index="0" place="Clustered" shape="Line"> <dataLabel style="Pattern"> <![CDATA[ $(desc) ]]> </dataLabel> </series> </elements> </frameChart>

Notice the dataLabel and the use of $(desc). So what happens next is kind of cool. I can run the chart as normal:

<cfchart chartWidth="400" chartHeight="400" title="Sales" font="arial" style="#chartxml#"> <cfchartseries type="line" query="q2" itemColumn="year" valueColumn="employees" seriesLabel="Employees" /> </cfchart>

And ColdFusion will ignore the string portion of the data. The charting engine will use this as the label:

This could have some interesting uses. For example, you could add descriptions for data points that have special meanings. For example, you could correlate your query to product releases, and for every year that had a product release, mention it: “Released Phaser Gun”. This would help give some context to the ups and downs of the chart.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless 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

Comments