Telerik blogs

The chart component for the Telerik Extensions for ASP.NET MVC is a rapidly expanding MVC component. Not only are we adding many new features, but we’re also increasing the available chart types. With the introduction of Q3 2011 we were able to start using two new chart types - Scatter and Scatter Line. Both types allow you to plot points anywhere on your chart area, as long as you provide each point with X and Y values. Let’s take a look at how you can implement these chart types, as well as take use of some new features introduced in Q3 2011 SP1.

Scattered Data Everywhere

As a starting point we can take a look at the scatter chart type and what awesome things we can do. One of the more important items with a chart is of course the data – why else would we have a chart? In an effort to include some short and sweet, but relevant, data I decided to go on Amazon.com and look up the Rating and Price of some DVD movies. Most of these ended up being a movie and its sequel, and we haven’t gone into genres yet, but I tried to get some variation in the titles! This can let me plot out Price against Rating, letting me see what movie gives me the most bang for my buck (after all, I want to be wise with my spending). So, what do we need to include in terms of the M portion of ASP.NET MVC? Title, Rating, and Price sound good to me:

public class MovieData
{
    public string Title { get; set; }
    public double Rating { get; set; }
    public double Price { get; set; }
}

I named this Model “MovieData”, which might not have me leaving with any awards for naming models, but it is still appropriate.

For this particular blog post I decided that I wanted to utilize Ajax binding with my chart, although you can definitely use server binding if you so prefer. So for the sake of me not forgetting to actually create some data (believe me, it’s happened too often ;)) let’s go ahead and just create a quick method in our controller that creates our list of movies. Now some of you might cringe at the idea of creating my list right in the controller, but this is for the sake of simplicity in this post, so put out those torches and lay down the pitchforks :) Here’s what this method looks like:

private List<MovieData> BuildMovieData()
{
    List<MovieData> movies = new List<MovieData>();
    movies.Add(new MovieData { Title = "Kung Fu Panda", Rating = 4.5, Price = 6.99 });
    movies.Add(new MovieData { Title = "Kung Fu Panda 2", Rating = 4.5, Price = 14.99 });
    movies.Add(new MovieData { Title = "Tron", Rating = 4.5, Price = 14.99 });
    movies.Add(new MovieData { Title = "Tron: Legacy", Rating = 4.0, Price = 18.15 });
    movies.Add(new MovieData { Title = "Harry Potter and the Deathly Hallows - Part 1", Rating = 4.0, Price = 7.47 });
    movies.Add(new MovieData { Title = "Harry Potter and the Deathly Hallows - Part 2", Rating = 3.0, Price = 14.99 });
    movies.Add(new MovieData { Title = "The Girl with the Dragon Tattoo", Rating = 4.0, Price = 11.99 });
 
    return movies;
}

So all this is doing is returning a list of our movies. While we’re in the controller, let’s create the ActionResult that will be used as our Ajax binding select, which will just return the Json representation of our data:

public ActionResult _SelectMovies()
{
    return Json(BuildMovieData());
}

Now that we’re done with our Model and Controller, all we have left is the View. Let’s just create a basic chart without any series for now:

@(Html.Telerik().Chart<MovieData>()
        .Name("ScatterChart")
        .Title("DVD Price vs. Rating")
        .DataBinding(dataBinding => dataBinding.Ajax().Select("_SelectMovies", "Chart"))
)

So we’ve set up our data binding, given our chart a name and a title. A good warm-up, but let’s actually create our scatter chart by defining our series:

@(Html.Telerik().Chart<MovieData>()
        .Name("ScatterChart")
        .Title("DVD Price vs. Rating")
        .DataBinding(dataBinding => dataBinding.Ajax().Select("_SelectMovies", "Chart"))
        .Series(series =>
        {
            series.Scatter("Price", "Rating");
        })
)

What you might notice here is that the strings I’m passing into the series are fields that I have defined in my Model, which is the way we let the scatter chart series know where to look for data. Here, the first parameter represents my X value – the DVD price – and the second parameter is my desired Y value – the DVD rating. I’ll show you what we can do with the Title (the last remaining property) later. If I were to run this as-is, we get the following:

First Scatter Chart

While yes, our data is represented, there’s a whole lot missing to make this a bit more intuitive. A couple of things stick out right away. Does the Legend provide a lot of help here? Do we actually need to have the half step markers for the Rating? Can we quickly glance at which axis represents what? Sure, one axis goes from 1 to 5, but what if we were looking at the bargain bin and had a rating which could be as high as 20 (can’t be specific enough with rating nowadays)? Let’s tweak some things around in our code to make this chart look better.

First, we can fix the issues I pointed out regarding both the X and Y axis by utilizing the XAxis and YAxis functions:

@(Html.Telerik().Chart<MovieData>()
        .Name("ScatterChart")
        .Title("DVD Price vs. Rating")
        .DataBinding(dataBinding => dataBinding.Ajax().Select("_SelectMovies", "Chart"))
        .Series(series =>
        {
            series.Scatter("Price", "Rating");
        })
        .XAxis(x => x
            .Title(title => title.Text("Price"))
            .Labels(labels => labels.Format("${0}")).Max(20))
        .YAxis(y => y.Title(title => title.Text("Rating")).Max(5))
)

What I have done here for each of them is defined the title text, which was introduced in Q3 2011 SP1, which gives our users some context as to what they’re viewing. Additionally, since the X-axis does deal with price I took the liberty of formatting the labels to include a “$” sign in front of every label. Finally I set max values for each axis, since I know that my rating can go between 0 and 5 I set 5 as the maximum for the Y axis while the X axis got a 20 since none of the titles went over $20. Refreshing our page in our browser (or reloading it completely) gives us this chart:

Second Scatter Chart

Still a few things we can change, but we’re getting there. In terms of immediate looks let’s just disable the Legend

@(Html.Telerik().Chart<MovieData>()
        .Name("ScatterChart")
        .Title("DVD Price vs. Rating")
        .DataBinding(dataBinding => dataBinding.Ajax().Select("_SelectMovies", "Chart"))
        .Series(series =>
        {
            series.Scatter("Price", "Rating");
        })
        .XAxis(x => x
            .Title(title => title.Text("Price"))
            .Labels(labels => labels.Format("${0}")).Max(20))
        .YAxis(y => y.Title(title => title.Text("Rating")).Max(5))
        .Legend(false)
)

Third Scatter Chart

Much better! This chart is coming along nicely.

Now, remember how I promised you I’d use the Title field? I know almost all of you were on the edge of your seats wondering what fun adventures I had in store for this field ;) Well, I want to add some interactivity to the chart so let’s take use of tooltips and have them give us the title of the movie! This gives us a nice context as to which point represents what movie. To do this let’s create a template for our tooltips:

.Tooltip(tooltip => tooltip
    .Visible(true)
    .Template("<#= dataItem.Title #>"))

Keep in mind that these are all client-side templates, and we utilize the “<#= … #>” syntax to indicate the beginning and end of our template. Also, using dataItem in our template allows us to grab fields from our Model, so I just used dataItem.Title to render the title in each tooltip. We could also plug in some HTML and let the Tooltip be bold:

.Tooltip(tooltip => tooltip
    .Visible(true)
    .Template("<#= '<strong>' + dataItem.Title + '</strong>'#>"))

Since we already used double quotes to define the string of our template we’ll just use single quotes around our strong tags. Now when we refresh our page we get to find out what each point in our chart represents:

Fourth Scatter Chart

There we have it! A quick and easy implementation of the Scatter chart which allows us to see which movies provide us with the best rating per cost ratio.

Line Them Up

We of course want to take a look at the scatter line chart, which gives us the ability to have our scatter points connected via a line. With the previous example this would look really weird, but we could utilize another Model and approach it in a similar way as with our scatter chart. Sales per year works pretty well, so let’s create a Model that has year and sales fields. So, we have our Model:

public class YearData
{
    public double Year { get; set; }
    public double Sales { get; set; }
}

Then we have our data creation function in our controller (again, still your torches and pitch forks :)):

private List<YearData> BuildYearData()
{
    List<YearData> sales = new List<YearData>();
    sales.Add(new YearData { Year = 2007, Sales = 10000 });
    sales.Add(new YearData { Year = 2008, Sales = 15000 });
    sales.Add(new YearData { Year = 2009, Sales = 30000 });
    sales.Add(new YearData { Year = 2010, Sales = 100000 });
    sales.Add(new YearData { Year = 2011, Sales = 500000 });
 
    return sales;
}

Return this to our View as Json via our ActionResult so that we can use Ajax Binding:

public ActionResult _SelectSales()
{
    return Json(BuildYearData());
}

Then we have the following chart declaration:

@(Html.Telerik().Chart<YearData>()
        .Name("ScatterLineChart")
        .Title("Sales per Year")
        .DataBinding(dataBinding => dataBinding.Ajax().Select("_SelectSales", "Chart"))
        .Series(series =>
        {
            series.ScatterLine("Year", "Sales");
        })
        .XAxis(x => x
            .Title(title => title.Text("Year")))
        .YAxis(y => y
            .Title(title => title.Text("Sales"))
            .Labels(labels => labels.Format("${0}")))
        .Legend(false)
        .Tooltip(tooltip => tooltip
            .Visible(true)
            .Template("<#= '<strong>Year: </strong>' + dataItem.Year + ', <strong>Sales: </strong>$' + dataItem.Sales #>"))
)

As we can see it’s pretty identical to what we had with the scatter chart type. The main difference is that in the series we use ScatterLine(“x”, “y”) instead of Scatter(“x”, “y”). We’re still passing the field names related to our desired X and Y values. We also removed the Max values from both the X and Y axis. Finally we expanded on the tooltip a little bit so we can use both the Year and Sales fields from our data item, allowing each point to have a detailed tooltip.

Final Notes

If you’re interested in more examples related to both the scatter and scatter line chart types I highly recommend checking out our demos

There are also several configuration options for defining the shape of the scatter points, as well as their style, which you can find more information about in our series documentation article.
Have you had a chance to utilize these chart types, or do you have good ideas for other sources of data? Feel free to share in the comments below!


Carl Bergenhem
About the Author

Carl Bergenhem

Carl Bergenhem was the Product Manager for Kendo UI.

Related Posts

Comments

Comments are disabled in preview mode.