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/
Related
I'm using ChartJS to display a timeseries as a bar chart. Is there some way to separate the tick resolution on the x axis from the width of the bars?
The snippet below demonstrates the problem; it is showing hourly data over one week. Because options.scales.xAxes[0].time.unit is set to day, the tick marks appear one per day but the bars are also one day wide. Setting the unit to hour makes the bars the right width but leads to hundreds of tick marks on the x axis and makes the labels unreadable.
Is there some way to have the best of both?
const RANGE = (a,b) => Array.from((function*(x,y){
while (x <= y) yield x++;
})(a,b));
labels = [];
for(var ii = 0; ii < 170; ii++) {
labels.push((1483228800 + ii * 3600) * 1000);
}
var canvas = document.getElementById('chart'),
ctx = canvas.getContext('2d'),
startingData = {
labels: labels,
datasets: [
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: RANGE(1, 170),
label: 'Data'
},
]
},
options = {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
}
}]
}
};
// Reduce the animation steps for demo clarity.
var myLiveChart = new Chart(ctx, {
type: 'bar',
data: startingData,
options: options
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
</head>
<body>
Hello, world.<br>
<canvas id="chart" width="500" height="300"></canvas>
</body>
</html>
The property unitStepSize might be what you are looking for.
Here is a JSFiddle with a example
As per the documentation:
The number of units between grid lines.
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;
I am creating a project using JavaScript. In my project i am integrating google charts, In my chart i want to show only five labels.I don't know how can i do this.Here is code:
var N = 10;
// Array filled with N values at '0'
var zero_array = [];
for (i = 0; i < N; i++)
zero_array.push(0);
// The data of the chart, describe the differents sets of data you want with points, colors...
var data = {
labels: zero_array,
datasets: [
{
showXLabels: 5,
label: zero_array, // Name of the line
data: zero_array, // data to represent
// The following makes the line way less ugly
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)",
}
]
};
// We wait for everything to be loaded
window.onload = function main() {
// Get the context of the canvas
var ctx = document.getElementById("line_example").getContext("2d");
// Create the Chart object
var line_example_chart = new Chart(ctx).Line(data);
// Used for the labels on the X axis
var label_idx = 1;
// Function to execute to remove then add a new random value to the chart
function rand_value() {
// Generate a random integer
var rand_val = Math.floor(Math.random() * 100);
// Remove the point at the far left of the chart
line_example_chart.removeData();
// Add the random value at the far right of the chart
line_example_chart.addData([rand_val], label_idx++);
}
// Run rand_value() every 2 seconds
window.setInterval(rand_value, 2000);
}
plunker link:
https://plnkr.co/edit/fat6hRS4lFnAEjoiSORW?p=preview
please help.
Looking at your code, just change N to 5:
var N = 5;
https://plnkr.co/edit/eJP4G6bYuGB5NaYvcQGX?p=preview
Please update below line and you can see only 5 nodes in your chart
var N = 5;
This is my first time usingchart.js to make line chat and it work on my localhost but when i uploaded it to a remote host i found out that the line chart was not showing so i inspected element and found this error in the console. please what could be the problem.
Uncaught TypeError: fn is not a function chart.js:501
this is the implementation script
<div id="graph-container"><canvas id="testLine"></canvas></div>
<script src="js/Chart.js"></script>
<script>
/*GLOBAL OPTIONS*/
Chart.defaults.global = {
// Boolean - Whether to animate the chart
animation: true,
// Number - Number of animation steps
animationSteps: 60,
animationEasing: "easeOutQuart",
// Boolean - If we should show the scale at all
showScale: true,
// Boolean - If we want to override with a hard coded scale
scaleOverride: false,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: null,
// Number - The value jump in the hard coded scale
scaleStepWidth: null,
// Number - The scale starting value
scaleStartValue: null,
// String - Colour of the scale line
scaleLineColor: "rgba(0,0,0,.1)",
// Number - Pixel width of the scale line
scaleLineWidth: 1,
// Boolean - Whether to show labels on the scale
scaleShowLabels: true,
// Interpolated JS string - can access value
scaleLabel: "<%=value%>",
// Boolean - Whether the scale should stick to integers, not floats even if drawing space is there
scaleIntegersOnly: true,
// Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: false,
// String - Scale label font declaration for the scale label
scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Scale label font size in pixels
scaleFontSize: 12,
// String - Scale label font weight style
scaleFontStyle: "normal",
// String - Scale label font colour
scaleFontColor: "#666",
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
// Boolean - Determines whether to draw tooltips on the canvas or not
showTooltips: true,
// Function - Determines whether to execute the customTooltips function instead of drawing the built in tooltips (See [Advanced - External Tooltips](#advanced-usage-custom-tooltips))
customTooltips: false,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for multiple tooltips
multiTooltipTemplate: "<%= value %>",
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){},
}
/*LINE CHART */
var lineData = {
labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: <?php echo (json_encode($allquery)); ?>
},
{
label: "Paid",
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)",
data: <?php echo (json_encode($monthpaid)); ?>
},
{
label: "Debt",
fillColor: "rgba(240,216,216,0.2)",
strokeColor: "rgba(240,216,216,1)",
pointColor: "rgba(240,216,216,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(240,216,216,1)",
data: <?php echo (json_encode($monthdebt)); ?>
}
]
};
var testChart = document.getElementById('testLine').getContext('2d');
var myLineChart = new Chart(testChart).Line(lineData);
myLineChart.options.responsive = false;
$("#testLine").remove();
$("#graph-container").html("<canvas id='testLine'></canvas>");
var testChart1 = document.getElementById('testLine').getContext('2d');
var myLineChart1 = new Chart(testChart1).Line(lineData);
I had the same issue but this answer to an identical question: Uncaught TypeError helped me fix mine. Try splitting the global configuration instead of wiping out all the global values when you declare a new object. Instead declare the variables separately like this...
Chart.defaults.global.animation = true;
Chart.defaults.global.animationSteps = 60;
Chart.defaults.global.animationEasing = "easeOutQuart";
Chart.defaults.global.showScale = true;
Chart.defaults.global.scaleOverride = false;
Chart.defaults.global.scaleSteps = null;
Chart.defaults.global.scaleStepWidth = null;
Chart.defaults.global.scaleStartValue = null;
Chart.defaults.global.scaleLineColor = "rgba(0,0,0,.1)";
Chart.defaults.global.scaleLineWidth = 1;
Chart.defaults.global.scaleShowLabels = true;
Chart.defaults.global.scaleLabel = "<%=value%>";
Chart.defaults.global.scaleIntegersOnly = true;
Chart.defaults.global.scaleBeginAtZero = false;
Chart.defaults.global.scaleFontFamily = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
Chart.defaults.global.scaleFontSize = 12;
Chart.defaults.global.scaleFontStyle = "normal";
Chart.defaults.global.scaleFontColor = "#666";
Chart.defaults.global.responsive = true;
Chart.defaults.global.maintainAspectRatio = true;
Chart.defaults.global.showTooltips = true;
Chart.defaults.global.customTooltips = false;
Chart.defaults.global.tooltipEvents = ["mousemove", "touchstart", "touchmove"];
Chart.defaults.global.tooltipFillColor = "rgba(0,0,0,0.8)";
Chart.defaults.global.tooltipFontFamily = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
Chart.defaults.global.tooltipFontSize = 14;
Chart.defaults.global.tooltipFontStyle = "normal";
Chart.defaults.global.tooltipFontColor = "#fff";
Chart.defaults.global.tooltipTitleFontFamily = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
Chart.defaults.global.tooltipTitleFontSize = 14;
Chart.defaults.global.tooltipTitleFontStyle = "bold";
Chart.defaults.global.tooltipTitleFontColor = "#fff";
Chart.defaults.global.tooltipYPadding = 6;
Chart.defaults.global.tooltipXPadding = 6;
Chart.defaults.global.tooltipCaretSize = 8;
Chart.defaults.global.tooltipCornerRadius = 6;
Chart.defaults.global.tooltipXOffset = 10;
Chart.defaults.global.tooltipTemplate = "<%if (label){%><%=label%>: <%}%><%= value %>";
Chart.defaults.global.multiTooltipTemplate = "<%= value %>";
Chart.defaults.global.onAnimationProgress = function() {};
Chart.defaults.global.onAnimationComplete = function() {};
This means you have problem with your options
check the values for example
tooltipTemplate: <%if (label){%><%=label%>: <%}%><%= value %>
You should turn off option asp_tags this probably happens only your online version and not local.
When asp tags is turned on it breaks on :
{"multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"}
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>"