Example of Back To Back Column in ASP.NET Core Charts Control
This Column Chart example grows two series to opposite sides of one axis, such as a population by age and sex.
@Html.UiChart(new UiChartOptions
{
Id = "backToBackChart",
Title = "Population by age group (thousands)",
Data = (IEnumerable<object>)ViewData["ChartData"],
Height = "380px",
OnAxisLabelRender = "absoluteLabel",
Legend = new UiChartLegend { Position = UiChartLegendPosition.Top },
Series = new List<UiChartSeries>
{
new UiChartSeries { Type = UiChartSeriesType.StackingBar, XName = "Age", YName = "Male", Name = "Male", StackGroup = "population" },
new UiChartSeries { Type = UiChartSeriesType.StackingBar, XName = "Age", YName = "Female", Name = "Female", StackGroup = "population" }
}
})
@using System.Linq
<script>
window.absoluteLabel = function (args) {
if (args.axis === 'y') { args.text = Math.abs(args.value).toLocaleString(); }
};
</script>
@Html.UiChart(new UiChartOptions
{
Id = "backToBackChart",
Title = "Population by age group (thousands)",
Data = (IEnumerable<object>)ViewData["ChartData"],
Height = "380px",
OnAxisLabelRender = "absoluteLabel",
Legend = new UiChartLegend { Position = UiChartLegendPosition.Top },
Series = new List<UiChartSeries>
{
new UiChartSeries { Type = UiChartSeriesType.StackingBar, XName = "Age", YName = "Male", Name = "Male", StackGroup = "population" },
new UiChartSeries { Type = UiChartSeriesType.StackingBar, XName = "Age", YName = "Female", Name = "Female", StackGroup = "population" }
}
})
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class ChartController : Controller
{
// The page is Views/Chart/BackToBackColumn.cshtml; it draws what ViewData holds.
public ActionResult BackToBackColumn()
{
ViewData["ChartData"] = new[]
{
new { Age = "0-14", Male = -310, Female = 295 }, new { Age = "15-29", Male = -420, Female = 405 },
new { Age = "30-44", Male = -380, Female = 390 }, new { Age = "45-59", Male = -290, Female = 310 },
new { Age = "60-74", Male = -190, Female = 225 }, new { Age = "75+", Male = -80, Female = 130 }
}.ToList();
return View();
}
}
}
@* Program.cs *@
builder.Services.AddControllersWithViews().AddLumenUIJson();
builder.Services.AddLumenUI();
// ...
app.UseLumenUI();
@* Views/_ViewImports.cshtml *@
@using Lumen.UI.Mvc
@addTagHelper *, Lumen.UI.Core
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@await RenderSectionAsync("scripts", required: false)
</body>
@* Charts with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@
Back to back: one series is given negative values, so it grows to the left while the other grows to the right from the same axis. OnAxisLabelRender shows the left side without its minus sign.