I am trying to get a BarChart appear using MVC, EF and json. For some reason the Bar Chart does not load and Google Chrome shows the following error "Uncaught TypeError: Cannot read property 'length' of undefined" in the console.
I am struggling to find the error in my code and hope someone can help me.
DashboardController
[AjaxOnly]
public ActionResult WeeklyLatenessSummary()
{
ChartHelper chart = new ChartHelper();
DateTime d = DateTime.Today;
int offset = d.DayOfWeek - DayOfWeek.Monday;
offset = (offset < 0) ? 6 : offset;
DateTime startDate = d.AddDays(-offset);
DateTime endDate = startDate.AddDays(7);
var data = (from a in _db.Attendances
join at in _db.AttendanceTypes on a.Type equals at.AttendanceTypeID
where a.Date >= startDate
&& a.Date < endDate
&& at.AttendanceTypeCode == "L"
group at by at.AttendanceTypeDescription into g
select new
{
value = g.Count()
}).ToList();
return Json(JsonConvert.SerializeObject(chart.PopulateBarChart("Weekly Lateness", data)), JsonRequestBehavior.AllowGet);
}
JSON Result
"[{\"label\":\"Weekly Lateness\",\"data\":\"3\",\"fillColor\":\"#F7464A\",\"strokeColor\":\"#F7464A\",\"highlightFill\":\"#FF5A5E\",\"highlightStroke\":\"#FF5A5E\"}]"
View
<div class="col-md-12">
<div class=" panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Weekly Lateness Summary</h3>
</div><!--End of panel-heading-->
<div class="panel-body">
<canvas id="weekly-lateness" width="650" height="300" class="center-block"></canvas>
</div><!--End of panel-body-->
</div><!--End of panel-->
</div><!--End of col-md-12-->
smChart.js
var ctx3 = $("#weekly-lateness").get(0).getContext("2d");
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke: true,
//Number - Pixel width of the bar stroke
barStrokeWidth: 2,
//Number - Spacing between each of the X value sets
barValueSpacing: 5,
//Number - Spacing between data sets within X values
barDatasetSpacing: 1,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
}
var getDaysInMonth = function (month, year) {
return new Date(year, month, 0).getDate();
}
var dates = [];
for (var i = 1; i <= getDaysInMonth(8,2015); i++) {
dates.push(i);
}
window.onload = function () {
$.ajax({
type: "GET",
dataType: "json",
url: "/Dashboard/WeeklyLatenessSummary/",
success: function (data) {
var json = JSON.parse(data);
var chartData = [];
for (var k in json) {
chartData.push(json[k])
}
if (chartData.length == 0) {
$('#weekly-lateness').hide();
$('#weekly-lateness').before("<h3 class='text-center'>No Data</h3>");
}
else {
var myPieChart3 = new Chart(ctx3).Bar(chartData, barChartOptions)
}
}
});
}
You're building the chartData variable incorrectly. For reference, here is what it should look like (from http://www.chartjs.org/docs/#bar-chart)
{
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
] };
The labels (not to be confused with label which is the series name)correspond to the x axis entries and the there is a datasets element for each series. Each series has as many entries in its data array as there are entries in labels
With the sample JSON you've given, here's one way to make the data appear
var chartData = {
labels: ['Potatoes'],
datasets: []
};
for (var k in json) {
chartData.datasets.push(json[k])
}
It will be easier to change it based on your requirements about what needs to be displayed and on which dimension.
I would venture to say it is bombing on your legend template when it is rendered.
datasets is undefined
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
Related
I am implementing line chart and I want to hide x'Axis label from line chart. I putted scaleFontSize: 0, , Than x'Axis and Y'axis labels are hide. But I want to hide only x'Axis label.
var lineOptions = {
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Number - Tension of the bezier curve between points
bezierCurveTension : 0.4,
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius : 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//Boolean - Re-draw chart on page resize
responsive: true,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
};
var lineData = {
labels: data,
datasets: [
{
pointHighlightStroke: "rgba(151,187,205,1)",
data: []
}
]
};
var getElement = document.getElementById("departuresChart2");
var ctx = getElement.getContext("2d");
$scope.myNewChart = new Chart(ctx).Line(lineData, lineOptions);
I am taking reference from http://www.chartjs.org/docs/#line-chart-introduction.
I want to hide only A'axis label.I have seen one link in stackoverflow Remove x-axis label/text in chart.js. But still I am not able to fixed. Thanks
You have to set scale.xLabels property of your chart (instance), to an empty array - [] (hides x-axis gridlines), or $scope.myNewChart.scale.xLabels.map(e => '') (shows x-axis gridlines), to hide x-axis labels.
Example
var lineOptions = {
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.4,
//Boolean - Whether to show a dot for each point
pointDot: true,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill: true,
//Boolean - Re-draw chart on page resize
responsive: true,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
};
var lineData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}]
};
var getElement = document.getElementById("departuresChart2");
var ctx = getElement.getContext("2d");
myNewChart = new Chart(ctx).Line(lineData, lineOptions);
myNewChart.scale.xLabels = []; //or set -> myNewChart.scale.xLabels.map(e => '');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="departuresChart2"></canvas>
I am trying to implement a chart of the chart.js library into my view. However, i am not able to display the chart as desired.
The particular part in my razor view:
<div class="col-md-8">
<p class="text-center">
<strong>Energy Consumption and Production: 1 Jan, 2016 - 30 Jul, 2016</strong>
</p>
<div class="chart-responsive">
<canvas id="trendChart" width="800" height="400"></canvas>
</div> #*/.chart-responsive*#
My Javascript code regarding the line chart:
$(function () {
var datachart = {
labels: [],
datasets: [
{
label: "Consumption",
backgroundColor: "rgba(215,220,67,0.3)",
borderColor: "rgba(220,220,220,0.7)",
borderWidth: 1,
hoverBackgroundColor: "rgba(220,220,220,1)",
hoverBorderColor: "rgba(220,220,220,0.5)",
data: []
},
{
label: "Production",
backgroundColor: "rgba(90,193,208,0.3)",
borderColor: "rgba(151,187,205,0.7)",
borderWidth: 1,
hoverBackgroundColor: "rgba(151,187,205,1)",
hoverBorderColor: "rgba(151,187,205,0.5)",
data: []
}
]
};
var trendChartOptions = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%=datasets[i].label%></li><%}%></ul>",
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>",
//Boolean - whether to make the chart responsive to window resizing
responsive: true
};
$.getJSON("/AdminLte/GetData", function (data) {
$.each(data, function (i, item) {
datachart.labels.push(item._DATE);
datachart.datasets[0].data.push(item.CONSUMPTION);
datachart.datasets[1].data.push(item.PRODUCTION);
})
});
var ctx = new Chart(document.getElementById("trendChart").getContext("2d")).Line(datachart, trendChartOptions);
});
And my controller method for dynamically filling the data:
public ContentResult GetData()
{
List<MeterDataTrendViewModel> meterDataTrend = new List<MeterDataTrendViewModel>();
var result =
from s in db.MeterDatas.ToList()
group s by new { s._DATE } into g
select new
{
read_date = g.Key._DATE,
CONSUMPTION = g.Sum(x => Convert.ToInt64(x.CONSUMPTION)),
PRODUCTION = g.Sum(x => Convert.ToInt64(x.PRODUCTION))
};
foreach(var res in result)
{
MeterDataTrendViewModel mdv = new MeterDataTrendViewModel();
mdv._DATE = res.read_date;
mdv.CONSUMPTION = res.CONSUMPTION.ToString();
mdv.PRODUCTION = res.PRODUCTION.ToString();
meterDataTrend.Add(mdv);
}
return Content(JsonConvert.SerializeObject(meterDataTrend), "application/json");
}
I`ve already debugged my js code and the data and labels array is filled correctly therefore my controller action is called. But there is only one datetime string displayed vertically so i guess it´s maybe aligned to the y-axis?
I can also fill the chart with static data and it´s displayed correctly. I cant figure out why my dynamic data isn´t displayed the right way.
I've managed to resolve this problem on my own with the following modifications.
$.getJSON("/AdminLte/GetData", function (data) {
$.each(data, function (i, item) {
chartlabels[i] = item._DATE;
cons[i] = item.CONSUMPTION;
prod[i] = item.PRODUCTION;
})
var ctx = new Chart(document.getElementById("trendChart").getContext("2d")).Line(datachart, trendChartOptions);
});
});
I am working on web socket related project.In following snippet I am getting the data coming from the server. I want to use the this data(in str variable) into another function. Kindly suggest any solution. Thank you in advance.
/*ON RECEIVING MESSAGES VIA WEBSOCKET FROM THE SERVER***/
ws.onmessage = function (event) {
var mySpan = document.getElementById("messageGoesHere");
var mySpan2 = document.getElementById("messageGoesHere2");
var str = event.data;
var array = str.split('|');
mySpan.innerHTML = parseInt(array[2])
mySpan2.innerHTML = parseInt(array[3]);
};
$(function () {
//Here I want to print the data
// and I can easily use this data to my chart
var areaChartData = {
//labels: ["January", "February", "March", "April", "May", "June", "July"],
labels: ["10", "20", "30", "40", "50", "60", "100"],
datasets: [{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}]
};
var areaChartOptions = {
showScale: true,
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
//Boolean - whether to make the chart responsive to window resizing
responsive: true
};
//-------------
//- LINE CHART -
//--------------
var lineChartCanvas = $("#lineChart").get(0).getContext("2d");
alert(lineChartCanvas);
var lineChart = new Chart(lineChartCanvas);
var lineChartOptions = areaChartOptions;
lineChartOptions.datasetFill = false;
lineChart.Line(areaChartData, lineChartOptions);
});
Do you mean something like this?
var mySpan = document.getElementById("messageGoesHere");
var mySpan2 = document.getElementById("messageGoesHere2");
function myCallback(event) {
var str = event.data;
var array = str.split('|');
mySpan.innerHTML = parseInt(array[2])
mySpan2.innerHTML = parseInt(array[3]);
};
/*ON RECEIVING MESSAGES VIA WEBSOCKET FROM THE SERVER***/
ws.onmessage = myCallback;
Using Chart js I am trying to pull data from Ajax call to supply to the Chart.
I found a few other postings where people have suggested delaying the canvas load but nothing has seemed to work. Currently this is the what I have below and the error that I get is
$(function () {
GetChartData();
function GetChartData() {
$.ajax({
url: ajaxURL,
method: 'GET',
dataType: 'json',
success: function (d) {
//-------------
//- BAR CHART -
//-------------
var barChartData = d;
var barChartCanvas = $("#barChart").get(0).getContext("2d");
var barChart = new Chart(barChartCanvas);
// console.log(datajson);
//barChartData.datasets[1].fillColor = "#00a65a";
//barChartData.datasets[1].strokeColor = "#00a65a";
//barChartData.datasets[1].pointColor = "#00a65a";
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
//scaleBeginAtZero: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke: true,
//Number - Pixel width of the bar stroke
barStrokeWidth: 2,
//Number - Spacing between each of the X value sets
barValueSpacing: 5,
//Number - Spacing between data sets within X values
barDatasetSpacing: 1,
multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>",
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
//Boolean - whether to make the chart responsive
responsive: true,
maintainAspectRatio: true
};
barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions);
}
});
}
});
UPDATE HERE SHOWING HOW NON AJAX WORKS
The below code is taking the results of the Ajax get request (which I got from dumping it to the console) and creating a "hard coded" version of the same thing. The only thing that should technically be different is one has the data loaded at time of the page and the second the data is loaded very briefly after.
var chartData = {
"labels": [
"April"
],
"datasets": [
{
"label": "Not Sure What to Put Here",
"fillColor": "#662B60",
"strokeColor": "#662B60",
"pointColor": "#662B60",
"pointStrokeColor": "#662B60",
"pointHighlightFill": "#662B60",
"pointHighlightStroke": "#662B60",
"data": [
1
]
},
{
"label": "Not Sure What to Put Here",
"fillColor": "#88B56E",
"strokeColor": "#88B56E",
"pointColor": "#88B56E",
"pointStrokeColor": "#88B56E",
"pointHighlightFill": "#88B56E",
"pointHighlightStroke": "#88B56E",
"data": [
1
]
},
{
"label": "Not Sure What to Put Here",
"fillColor": "#48CA2B",
"strokeColor": "#48CA2B",
"pointColor": "#48CA2B",
"pointStrokeColor": "#48CA2B",
"pointHighlightFill": "#48CA2B",
"pointHighlightStroke": "#48CA2B",
"data": [
0.83
]
}
]
};
//-------------
//- BAR CHART -
//-------------
var barChartData = chartData;
var barChartCanvas = $("#barChart").get(0).getContext("2d");
var barChart = new Chart(barChartCanvas);
//barChartData.datasets[1].fillColor = "#00a65a";
//barChartData.datasets[1].strokeColor = "#00a65a";
//barChartData.datasets[1].pointColor = "#00a65a";
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
//scaleBeginAtZero: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke: true,
//Number - Pixel width of the bar stroke
barStrokeWidth: 2,
//Number - Spacing between each of the X value sets
barValueSpacing: 5,
//Number - Spacing between data sets within X values
barDatasetSpacing: 1,
multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>",
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
//Boolean - whether to make the chart responsive
responsive: true,
maintainAspectRatio: true
};
barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions);
Update
I changed from the min version of chart.js to the full version so I could see where exactly it was erroring out at.
Here is the image from chrome console
The problem is that when your code executes, the canvas has not been created yet.
You should wrap your code inside a function and assign that function to window.onload event. You can see the sample code below.
window.onload = function() {
var ctx = document.getElementById("myChart");
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "2015",
data: [10, 8, 6, 5, 12, 8, 16, 17, 6, 7, 6, 10]
}]
}
})
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
</body>
</html>
Found the answer,
The Ajax results has to be parsed first.
resulting fix
var barChartData = JSON.parse(d);
running the following worked for me:
window.onload = function () {
}
For other users who have this problem, make sure your container canvas element exists, when called upon.
You may try putting the Chart.JS script tag and other custom JS scripts just before the end of **<**/body> tag.
It looks like you're using an object that doesn't exist, well at least I cant see it, datasets. I can only see length being called on this object, unless there's missing code?
I can see you assign d to barChartData
var barChartData = d;
So, you might want to replace the instances of datasets with barChartData.
It's an old question but, I had this issue as well and in my case my data was length = 0. I solved this just adding a validation before calling the the graph:
if (barChartData.length > 0)
{
objChart = Morris.Bar({....
}
I am using a chart in my page using chart.js I have on my x axis dates while on my y axis values(cost). I want to keep the line chart continue its value until there is a change and have coded for that. Here is the output
In this as marked if the value is same I have dots plotted. I have an option to remove all dots but I want to remove dots if the value is same as previous.(there is no change). I would like to know if this is doable. If please guide me how to go for it?
Its not the same as marked for being duplicate...
I want them to be true or flse based on value. If value is zero or same as previous then dont display dot
HERE IS MY CODE
as.dashboard = {};
as.dashboard.adjustWidgetsHeight = function () {
var maxHeight = 0;
$(".panel-widget .panel-heading").height('auto');
$(".panel-widget .panel-heading").each(function () {
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$(".panel-widget .panel-heading").height(maxHeight);
};
as.dashboard.initChart = function () {
var data = {
labels: dayss,
//Number - Tension of the bezier curve between points
bezierCurveTension : 0.4,
datasets: [
{
label: "Machine costs History",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
bezierCurve : false,
data: costVariations
}
, {
label: "My third dataset", // This ONE IS DUMMY IT HELPS IN
// SOLVING OVERLAPPING TOOL TIPS
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, {
responsive: true,
maintainAspectRatio: false,
tooltipTemplate: "<%if (value!=0){%><%= value %> <%= units %> <%}%>",
multiTooltipTemplate: "<%if (value!=0){%><%= value %> <%= units %> <%}%>",
});
};
$(document).ready(function () {
as.dashboard.adjustWidgetsHeight();
as.dashboard.initChart();
});
...
for (var i = 1; i <= data.datasets[0].data.length - 1; i++)
if (data.datasets[0].data[i - 1] === data.datasets[0].data[i])
myChart.datasets[0].points[i].display = false;
where myChart is your chart object
Fiddle - http://jsfiddle.net/3tok57dL/