Javascript window.onload not displaying charts with Chart.js and Flask - javascript

I'm new to Javascript and now I'm tasked to display charts with Chart.js. I did grouping in Python and used Flask to build the web app. However, my chart is somehow not displayed and I'm not sure why.
HTML
<canvas id="barchart2" width="600" height="400"></canvas>
JS
<script>
var config = {
type: 'bar',
labels : [
"52",
"51",
"54",
"53",
"46",
"82",
"57",
"48",
"50",
"56",
],
datasets : [
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data : [
611,
18,
11,
10,
9,
8,
6,
3,
2,
2,
]
}
]
},
options: {
legend: {
display: true,
},
title: {
display: true,
text: 'Top 10 District in Singapore',
}
},
};
window.onload = function() {
var ctx = document.getElementById("barchart2").getContext("2d");
window.myBar = new Chart(ctx, config);
};
</script>
When I used this JS instead
var barData = {
labels : [{% for item in lbl1 %}
"{{item}}",
{% endfor %}],
datasets : [
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data : [{% for item in val1 %}
{{item}},
{% endfor %}]
}
]
}
// get bar chart canvas
var mychart = document.getElementById("barchart2").getContext("2d");
// draw bar chart
new Chart(mychart).Bar(barData);
It worked perfectly (note: without options. I tried to add options, but the options doesn't show although the charts still appears. That's why I wanna change to this format instead).
But when I use the window.onload function, the chart doesn't appear at all.
Would appreciate your help. Thanks!

Could you paste here the complete generated JS code with the data? Or review your data, because I think that might be the problem somehow.
Here's a JSFiddle with your original code (sans your data) that works:
https://jsfiddle.net/wj80597q/5/
var config = {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
options: {
legend: {
display: true,
},
title: {
display: true,
text: 'Top 10 District in Singapore',
}
},
};
(function() {
var ctx = document.getElementById("barchart2").getContext("2d");
window.myBar = new Chart(ctx, config);
})()

Related

I don't want to auto reflect chart with $watch in angulars js?

Right now I am implementing line chart in angular js. And I have written one directive for this, So it is working fine, But when I am putted $watch in this directive then every time chart will updating continuously. I want to use $watch for some dynamic change after loaded the page.
angular.module('app.abc').directive('linechart', function () {
return {
restrict: 'A',
template:'',
link: function (scope, element, attributes) {
scope.$watch(function(){
var lineOptions = {
scaleShowGridLines : true,
scaleGridLineColor : "rgba(0,0,0,.05)",
scaleGridLineWidth : 1,
bezierCurve : true,
};
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)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var ctx = element[0].getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
})
}
}
});
<canvas style="display: block;" linechart height="120" ></canvas>
Line chart reflecting updates is contiguously. But I don't want to reflection continuously. I have tried to put my ctx object outside of $watch, but chart is not showing anything. Actually I am new in angular js and also new in directives. Please give me idea how handle this directive with $watch. I have seen one demo(based on javascript) example https://codepen.io/SitePoint/pen/mJRrKw

chart.js 2, animate right to left (not top-down)

the jsfiddle below shows the problem.
The first data inserts are fine, but when the length of the data set is capped at 10 you see the undesired behaviour where data points are animated top-down instead of moving left. It's extremely distracting.
http://jsfiddle.net/kLg5ntou/32/
setInterval(function () {
data.labels.push(Math.floor(Date.now() / 1000));
data.datasets[0].data.push(Math.floor(10 + Math.random() * 80));
// limit to 10
data.labels = data.labels.splice(-10);
data.datasets[0].data = data.datasets[0].data.splice(-10);
chart.update(); // addData/removeData replaced with update in v2
}, 1000);
Is there a way to have the line chart move left having the newly inserted data point appear on the right? As opposed to the wavy distracting animation?
thanks
This code uses streaming plugin and works as expected.
http://jsfiddle.net/nagix/kvu0r6j2/
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming#1.5.0/dist/chartjs-plugin-streaming.min.js"></script>
var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(95,186,88,0.7)",
borderColor: "rgba(95,186,88,1)",
pointBackgroundColor: "rgba(0,0,0,0)",
pointBorderColor: "rgba(0,0,0,0)",
pointHoverBackgroundColor: "rgba(95,186,88,1)",
pointHoverBorderColor: "rgba(95,186,88,1)",
data: []
}]
},
options: {
scales: {
xAxes: [{
type: 'realtime'
}]
},
plugins: {
streaming: {
onRefresh: function(chart) {
chart.data.labels.push(Date.now());
chart.data.datasets[0].data.push(
Math.floor(10 + Math.random() * 80)
);
},
delay: 2000
}
}
}
});
You should use 2.5.0 chartsjs
here it works :
http://jsfiddle.net/kLg5ntou/93
var data = {
labels: ["0", "1", "2", "3", "4", "5", "6"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(95,186,88,0.7)",
strokeColor: "rgba(95,186,88,1)",
pointColor: "rgba(0,0,0,0)",
pointStrokeColor: "rgba(0,0,0,0)",
pointHighlightFill: "rgba(95,186,88,1)",
pointHighlightStroke: "rgba(95,186,88,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {type: 'line', data: data});
setInterval(function () {
chart.config.data.labels.push(Math.floor(Date.now() / 1000));
chart.config.data.datasets[0].data.push(Math.floor(10 + Math.random() * 80));
// limit to 10
chart.config.data.labels.shift();
chart.config.data.datasets[0].data.shift();

Chartjs v2 xAxes label overlap with scaleLabel

The chart js v2 is overlapping with is there a way to move the labelString of scaleLabel further down so that it does not overlap.Please view the screen shot marked in yellow and red part.
Part of the code is as following
scales: {
xAxes: [{
display: true,
ticks: {
autoSkip: false,
autoSkipPadding: 20
},
scaleLabel: {
display: true,
labelString: "ProductName(ProductName)"
}
}],
There are two possible solutions to your problem:
1: This is for a line chart, but can easily tailored to a bar chart.
The legend is part of the default options of the ChartJs library. So
you do not need to explicitly add it as an option.
The library generates the HTML. It is merely a matter of adding that
to the your page. For example, add it to the innerHTML of a given DIV.
(Edit the default options if you are editing the colors, etc)
<div>
<canvas id="chartDiv" height="400" width="600"></canvas>
<div id="legendDiv"></div>
</div>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "The Flash's Speed",
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: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Superman's Speed",
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: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
2: Adding a legend template in chart options
You'll also need to add some basic css to get it looking ok.
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% 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>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
Either of these two options will work.
In your case the legend code will look something like this
(Assuming you already have a BarChart Generated)
<div id="legendDiv"></div>
document.getElementById("legendDiv").innerHTML = BarChart.generateLegend();
Then use css to format the legend however you would prefer (including adding spacing between the legend in the chart)

Line chart: align x axis (timestamps) for multiple data sets

I have run my head into a brick wall with this one. I have a data set that tracks three data points over time. These data points can change independently of each other. I am trying to show the history of these changes in a line chart but I have yet to find out how to make a common x axis for the three.
The data is returned like this:
{
"Default": {
"Values": [
999,
799,
999
],
"Timestamps": [
"2015-03-01T03:31:16+00:00",
"2015-03-01T07:21:43+00:00",
"2015-03-01T14:02:22+00:00"
]
},
"Current": {
"Values": [
399,
849
],
"Timestamps": [
"2015-03-01T01:15:22+00:00",
"2015-03-01T21:30:43+00:00"
]
},
"CurrentPremium": {
"Values": [
500,
345,
200,
500
],
"Timestamps": [
"2015-02-01T14:24:00+00:00",
"2015-03-01T00:13:28+00:00",
"2015-03-01T09:56:43+00:00",
"2015-03-01T12:00:04+00:00"
]
}
}
The returned values indicate when this value changed from its previous value.
I am using a linechart from chartjs to visualize the data. For that I need to supply a common list of labels that match the data points for the lines so I need to align these three data sets somehow but I can't figure out how to achieve this.
I would use a library like lodash (to make utility things quicker) to pre process the data into a flat list of all timestamps and then for each dataset a matching list of values recording null if that data set does not have a timestamp from the merged flat list of all timestamps.
I have also added an option to my fork of chart js which would be useful here which would be to then populate sparse data to the lines still connect and you are not left with floating points that can be hard to see.
var datasets = {
"Default": {
"Values": [
999,
799,
999
],
"Timestamps": [
"2015-03-01T03:31:16+00:00",
"2015-03-01T07:21:43+00:00",
"2015-03-01T14:02:22+00:00"
]
},
"Current": {
"Values": [
399,
849
],
"Timestamps": [
"2015-03-01T01:15:22+00:00",
"2015-03-01T21:30:43+00:00"
]
},
"CurrentPremium": {
"Values": [
500,
345,
200,
500
],
"Timestamps": [
"2015-02-01T14:24:00+00:00",
"2015-03-01T00:13:28+00:00",
"2015-03-01T09:56:43+00:00",
"2015-03-01T12:00:04+00:00"
]
}
};
//merge and sort all timestamps in to one array (used lodash here just to make things easy
var timestamps = _.chain(datasets).pluck("Timestamps").reduce(function(previous, current, index) {
return previous.concat(current)
}).unique().sortBy(function(timestamp) {
return new Date(timestamp)
}).value();
//set up base chart data with colours
var chartDatasets = [{
fillColor: "rgba(220,120,120,0.2)",
strokeColor: "rgba(220,120,120,1)",
pointColor: "rgba(120,120,120,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
}, {
fillColor: "rgba(20,120,120,0.2)",
strokeColor: "rgba(20,120,120,1)",
pointColor: "rgba(20,120,120,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
}, {
fillColor: "rgba(120,120,120,0.2)",
strokeColor: "rgba(120,120,120,1)",
pointColor: "rgba(120,120,120,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
}]
//go through each dataset from server,
//for each dataset go through it's time stamps,
//go through the merged timestamps and if the timestamp is prresent in the dataset record the value other wise record null so we
//end up with a flat list of data that matches the flat time stamps
var datasetsIndex = 0;
_.forEach(datasets, function(dataset, key) {
var data = [];
_.forEach(timestamps, function(timestamp) {
var dataToPush = null;
_.forEach(dataset.Timestamps, function(datasetTimestamp, datasetTimestampIndex) {
if (datasetTimestamp === timestamp) {
dataToPush = dataset.Values[datasetTimestampIndex];
}
});
data.push(dataToPush);
});
chartDatasets[datasetsIndex].label = key;
chartDatasets[datasetsIndex].data = data;
datasetsIndex++;
});
var chartData = {
labels: timestamps,
datasets: chartDatasets
};
var chart = new Chart(document.getElementById("chart").getContext("2d")).Line(chartData, {
populateSparseData: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.3.1/lodash.js"></script>
<script src="http://quincewebdesign.com/cdn/Chart.js"></script>
<canvas id="chart" width="400" height="400"></canvas>

chart js tooltip how to control the data that show

I'm using chart.js plugin and using a group chart by bar view.
when i hover a group of bars i can see a tooltip that show me the data of this bars.
but i what to change the tooltip to show my only single data when I'll hover the bar data.
and I what to show diffrent data info.
jsfiddle example
var ctx = document.getElementById("errorChart").getContext("2d");
var data = {
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, 0, 0, 0, 0, 0, 0]
},
{
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]
}
]
};
var myBarChart = new Chart(ctx).Bar(data);
You could extend the bar graph to include this functionality. By default it will return both bars at the index you have hovered over, it will also check for multiple bars at the area you hovered before creating the tooltip and put any extras in that were missing.
So to do this you will need to override two functions getBarsAtEvent and showToolTip here is an example and fiddle
I have tried to make it clear the two important areas that have changed look at the comments in the extended bar type. Small changes were also made to any reference of the helpers as before they were within the scope but now they need to explicitly call Chart.helpers
Chart.types.Bar.extend({
name: "BarOneTip",
initialize: function(data){
Chart.types.Bar.prototype.initialize.apply(this, arguments);
},
getBarsAtEvent : function(e){
var barsArray = [],
eventPosition = Chart.helpers.getRelativePosition(e),
datasetIterator = function(dataset){
barsArray.push(dataset.bars[barIndex]);
},
barIndex;
for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
//change here to only return the intrested bar not the group
barsArray.push(this.datasets[datasetIndex].bars[barIndex]);
return barsArray;
}
}
}
return barsArray;
},
showTooltip : function(ChartElements, forceRedraw){
console.log(ChartElements);
// Only redraw the chart if we've actually changed what we're hovering on.
if (typeof this.activeElements === 'undefined') this.activeElements = [];
var isChanged = (function(Elements){
var changed = false;
if (Elements.length !== this.activeElements.length){
changed = true;
return changed;
}
Chart.helpers.each(Elements, function(element, index){
if (element !== this.activeElements[index]){
changed = true;
}
}, this);
return changed;
}).call(this, ChartElements);
if (!isChanged && !forceRedraw){
return;
}
else{
this.activeElements = ChartElements;
}
this.draw();
console.log(this)
if (ChartElements.length > 0){
//removed the check for multiple bars at the index now just want one
Chart.helpers.each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: Chart.helpers.template(this.options.tooltipTemplate, Element),
chart: this.chart
}).draw();
}, this);
}
return this;
}
});
then to use it just do what you did before but use BarOneTip (call it whatever you like, what ever is in the name attribute of the extended chart will be available to you.
var ctx = document.getElementById("errorChart").getContext("2d");
var data = {
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, 0, 0, 0, 0, 0, 0]
},
{
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]
}
]
};
var myBarChart = new Chart(ctx).BarOneTip(data);
I should mention that if chartjs gets updated you would need to manually put any changes to the functions into the overridden ones

Categories