Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic series in Kendo UI Bar Chart

I' ve spent a few hours on this problem and can't seem to figure out how to solve it.

I'm trying to create a stacked bar chart like this:

http://demos.kendoui.com/dataviz/bar-charts/stacked-bar.html

I'm using ASP.NET MVC (Razor).

Here is some sample code:

@(Html.Kendo().Chart()
    .Name("chart")
    .Title("chart")
    .Legend(legend => legend
        .Position(ChartLegendPosition.Bottom)
    )
    .SeriesDefaults(seriesDefaults =>
        seriesDefaults.Bar().Stack(true)
    )
    .Series(series =>
    {

        series.Bar(new double[] { 4 });
        series.Bar(new double[] { 2 });
        series.Bar(new double[] { 7 });

    })
    .CategoryAxis(axis => axis
        .Categories("Machine")
        .MajorGridLines(lines => lines.Visible(false))
    )
    .ValueAxis(axis => axis
        .Numeric()
        .Labels(labels => labels.Format("{0}"))
        .Max(24)
        .Line(line => line.Visible(false))
        .MajorGridLines(lines => lines.Visible(true))
    )
    .Tooltip(tooltip => tooltip
        .Visible(true)
        .Template("#= series.name #: #= value #")
    )
)

Now here is the problem I'm facing. This line of code:

series.Bar(new double[] { 4 });

adds value 4 to my chart. The problem is that, in the moment I'm writing the code, I don't know how many series there will be. That will be determined by the data in the database. For example, if there will be 5 records, I need there to be 5 series added, and so on.

Do you have any idea how to add those series?

Cheers!

like image 594
cah1r Avatar asked Oct 15 '13 09:10

cah1r


1 Answers

For others having simmilar problem I think I found a workaround .

@{
List<List<int>> myList = new List<List<int>>();
myList.Add(new List<int> { 7 });
myList.Add(new List<int> { 2 });
myList.Add(new List<int> { 3 });
myList.Add(new List<int> { 4 });
}        

...

.Series(series =>
        {
            for (int i = 0; i < 4;i++ )
            {
                series.Bar(myList[i]);
            }

        })
...

Since Kendo Ui chart wants to get List I had to create List of Lists. Than use for loop to iterate over desired data. This way data can be stacked in only one category.

It allows the number of series to be a variable (passed to the view through model)

like image 150
cah1r Avatar answered Sep 27 '22 19:09

cah1r