我正在使用CanvasJs渲染图表,它现在正常工作。虽然我不确定,但它是否以适当的方式在图表中显示数据。这是我正在使用的逻辑:
var query = from c in GetProducts()
group c by c.Type into g
select new
{
Type = g.Key,
Count = g.Count()
};
double val = 0;
string valNo = "";
List<DataPoint> dataPoints = new List<DataPoint>();
foreach (var item in query)
{
val = ((Convert.ToDouble(item.Count) / 30) * 100); //The logic - Tracks user login for 30 days. For the time being, days are fixed to 30 days
valNo = val.ToString("#.##");
DataPoint aDataPoint = new DataPoint();
aDataPoint.y = valNo;
aDataPoint.legendText = item.Type;
aDataPoint.label = item.Type;
dataPoints.Add(aDataPoint);
ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
}
控制器和型号:
public List<UserType> GetProducts()
{
List<UserType> aLst = new List<UserType>()
{
new UserType() { UserId = 1001, Type = "Admin" },
new UserType() { UserId = 1002, Type = "User" },
new UserType() { UserId = 1003, Type = "Admin" },
new UserType() { UserId = 1004, Type = "User" },
new UserType() { UserId = 1005, Type = "Admin" },
new UserType() { UserId = 1006, Type = "Operator" },
new UserType() { UserId = 1007, Type = "Operator" },
new UserType() { UserId = 1008, Type = "Admin" },
new UserType() { UserId = 1009, Type = "Operator" },
new UserType() { UserId = 1010, Type = "Admin" },
new UserType() { UserId = 1011, Type = "Operator" },
new UserType() { UserId = 1012, Type = "Vendor" },
new UserType() { UserId = 1013, Type = "Vendor" },
new UserType() { UserId = 1014, Type = "Admin" },
new UserType() { UserId = 1015, Type = "Admin" },
new UserType() { UserId = 1016, Type = "Admin" }
};
return aLst;
}
public class DataPoint
{
public string y { get; set; }
public string legendText { get; set; }
public string label { get; set; }
}
观点:
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer"></div>
<script type="text/javascript">
debugger;
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Frequently Visited User Types (Sample)"
},
animationEnabled: true,
legend: {
verticalAlign: "center",
horizontalAlign: "left",
fontSize: 20,
fontFamily: "Helvetica"
},
theme: "theme2",
data: [
{
type: "pie",
indexLabelFontFamily: "Garamond",
indexLabelFontSize: 20,
indexLabel: "{label} {y}%",
startAngle: -20,
showInLegend: true,
toolTipContent: "{legendText} {y}%",
dataPoints: @Html.Raw(ViewBag.DataPoints),
} ]
});
chart.render();
};
</script>
现在我得到的示例图片:
我有点担心上面显示的图表我的意思是提供的数据和计算。尽管我的逻辑工作但是在图表中,管理员占据了图表的26.67%,而且似乎它占了50%。那么数据在图表中的表现是否完美?令我困惑的是 - Canvas JS Chart。它在最后计算所有类型值为100%,它覆盖整个图表。那么它取决于类型数字还是我在这里遗漏了什么?任何建议或建议都会非常值得赞赏 - 谢谢。
答案 0 :(得分:3)
您在数据点中的数据是:admin,26.67;用户,6.67;运营商,13.33和供应商,6,67。所以admin%是26.67 / 53.33 * 100 = 50%。所以饼图是完全正确的。这取决于您想要在图表中显示的内容。管理员在16岁时出现8次,必须用半个饼来表示。由于您的计算次数/ 30 * 100,标签值会有所不同。