Adding sparklines to your MVC site using the Google Chart API

Sparklines present trends and variations associated with some measurement in a very compact form.  The term & concept was proposed by Ed Tufte.  This form of information graphic has become very popular for dashboards.  In this post, I'll show how add sparklines to your site using a custom HTML Helper method to generate code accessing the Google Chart API. In my next post, I'll show you how to add sparklines using the .NET charting API.

The folks over at Data Driven wrote a post about using the Google Chart API to render a sparkline.  The following shows how to take this concept & make it reusable by your MVC application.

Code for the extension method:

        public static MvcHtmlString DrawSparkline(this HtmlHelper helper, int width, int height, IEnumerable<int> plotData,
            string bgColor, string lineColor, string labelColor)
        {
            int? max = plotData.Max();
            int? min = plotData.Min();
            string list = String.Join(",", plotData);
            string sparkUrl = "<img src='http://chart.apis.google.com/" +
                 "chart?cht=lc&chf=bg,s,{6}&cgh=0,50,1,0&chds={0},{1}&chs={2}x{3}&chd=t:{4}&chco={8}" +
                 "&chls=1,1,0&chm=o,{7},0,20,4&chxt=r,x,y&chxs=0,{7},11,0,_|1,{7},1,0,_|2,{7},1,0,_&chxl=0:|{5}|1:||2:||'/>";
            string sparkLine = String.Format(sparkUrl, min, max, width, height, list, plotData.Last(), bgColor, labelColor, lineColor);
            return MvcHtmlString.Create(sparkLine);
        }

And here is an example of calling the HTML helper from a MVC Razor template:

@Html.DrawSparkline(70, 20, new int[14] { 1, 4, 2, 6, 20, 30, 1, 23, 14, 2, 41, 2, 33, 21 }, "ffffff", "999999", "990000")

Which produces the following sparkline:

1 Comment

Comments have been disabled for this content.