屏蔽ui图表:动态生成序列

本文关键字:动态 ui 图表 屏蔽 | 更新日期: 2023-09-27 17:58:05

有没有一种方法可以在不提前知道有多少系列的情况下将系列添加到图表中?例如,我想在X轴上按月份绘制一个年份的变量。每一年都是一个系列。

我想过在按年份分组时绑定到IEnumerable,并在每个分组项上创建一个系列,但我真的无法想象代码。

屏蔽ui图表:动态生成序列

我用一个自定义助手(HtmlHelper扩展方法)实现了这一点。我把一个例子改编自http://demos.shieldui.com/aspnet/aspnet-chart/programmatic-chart-creation,但该示例适用于ASP.NET web窗体。我在做MVC。我的解决方案涉及使用ChartBuilder<>对象。

public static class ChartExtensions
{
    public static ChartBuilder<PropertyPivotAverageAmountPerMonth_Result> AnnualComparison(this HtmlHelper html, int id)
    {
        MyDatabaseEntities db = new MyDatabaseEntities();
        var results = db.PropertyPivotAverageAmountPerMonth(id);
        ChartBuilder<PropertyPivotAverageAmountPerMonth_Result> chart = new ChartBuilder<PropertyPivotAverageAmountPerMonth_Result>(html, results);
        chart.AxisX(axisX => axisX.CategoricalValues("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"));
        chart.PrimaryHeader(header => header.Text("Annual Cost Comparisons"));

        foreach (var year in results)
        {
            chart.DataSeries(s => s.Line()
                .CollectionAlias(year.Year.ToString())
                .Data(new object[]
                    {
                        new { x=0, y=year.C1 },
                        new { x=1, y=year.C2 },
                        new { x=2, y=year.C3 },
                        new { x=3, y=year.C4 },
                        new { x=4, y=year.C5 },
                        new { x=5, y=year.C6 },
                        new { x=6, y=year.C7 },
                        new { x=7, y=year.C8 },
                        new { x=8, y=year.C9 },
                        new { x=9, y=year.C10 },
                        new { x=10, y=year.C11 },
                        new { x=11, y=year.C12 }
                    }));
        }
        return chart;
    }