I retrieved the years and values from the database and successfully drew the graph. I managed to display the X and Y axis values in the tooltip. Now I want to display in the tooltip the percentage of what the user spent compared to last year. Did he spend more/less compared to last year and how much less.
Part of chart for tooltip:
<ChartTooltipSettings Enable="true" Fill="gray">
<Template>
@{
var data = context as ChartTooltipInfo;
<b>@data.X : @data.Y</b>
}
</Template>
</ChartTooltipSettings>
The percentage function works fine. The only problem is that I don't know how to display its value in the tooltip. So I want the format: "X value: Y value" and "You spent p% less/more than last year", less/more depends on it's value. If it's negative write less, if it's positive write more.
Part for calculating the percentage:
public class YearsData
{
public int Year { get; set; }
public decimal CostValue { get; set; }
public decimal PercentageIncrease { get; set; }
public void CalculatePercentageIncrease(decimal previousYearCost)
{
if (previousYearCost != 0)
{
PercentageIncrease = ((CostValue - previousYearCost) / previousYearCost) * 100;
}
else
{
PercentageIncrease = 0;
}
}
}
CostYears = await CostService.GetCostsAsync() ?? new List<CostDTO>();
decimal previousYearCost = 0;
foreach (var year in CostYears.Select(c => c.CreatedAt.Year).Distinct().OrderBy(year => year))
{
var yearCost = await CostService.GetCostsByYearAsync(year);
var costs = yearCost ?? new List<CostDTO>();
var yearSum = costs.Sum(c => c.Value);
var yearsData = new YearsData { Year = year, CostValue = yearSum };
costByYears.Add(yearsData);
yearsData.CalculatePercentageIncrease(previousYearCost);
previousYearCost = yearSum;
}
I tried a lot of different things, but nothing works properly.
You can use the TooltipRender event and manipulate the tooltip output with your class there.
Your event handler might be something like: