How to create float charts with chartjs? - javascript

I tried creating float charts with chartjs but it does not seem to work. I tried copying the same example as they have http://pravopys.net/chartjs/samples/charts/bar/vertical.html but mine does not render at all or throw any errors.
var myBarChart = new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ['January', 'February', 'March'],
datasets: [
{
label: "Population (millions)",
data: [
[-2, 5],
[-20, 70],
[30, 80]
],
backgroundColor: "rgba(75, 192, 192, 0.2)",
borderColor: "rgba(75, 192, 192, 1)",
borderWidth: 1,
fill: false,
lineTension: 0,
type: "bar"
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}
}
});
Not sure what I'm doing wrong here. The example shows the data structure for the dataset being used exactly how I'm using it.
Any help is greatly appreciated.
Plunker link: http://www.plnkr.co/edit/bD1MgVvjuq7B4RM5Qcmh?p=preview

You need a 2d context to draw the chart on. Here's a working example:
Do these 2 changes in your code:
HTML
<canvas id="bar-chart" width="400" height="400"></canvas>
Javascript
var ctx = document.getElementById("bar-chart").getContext("2d");
var myBarChart = new Chart(ctx, ...)
Source: https://www.chartjs.org/docs/latest/#creating-a-chart

Related

Line chart plotting multiple points for duplicate data on x and y axis using chart.js

i am a beginner working on angular8 application and using chart.js version ^2.9.3, i created a chart based on the below data.
Code Sample for creating Line chart with the data i have:
const labels = [65, 65, 80, 80, 56, 55, 40]
const data = {
labels: labels,
datasets: [{
label: 'My First Dataset',
data: [67, 67, 81, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
};
i have picked up the sample line chart reference from the samples given on chartjs.org and modified the kind of duplicate data i get from my db.
I want to get a single point for duplicate x-axis and y-axis value rather than creating multiple points, how can i do that in Line chart?
I have attached the sample for reference.
The best thing you can do is manipulate your data beforehand by removing the duplicate values from your data array, the other option you can use is the object notation in combination with a linear x axis, this will still plot the point double but it will put it in the same place
var options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: 79,
y: 80
}, {
x: 80,
y: 81
}, {
x: 80,
y: 81
}, {
x: 81,
y: 77
}],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
},
options: {
scales: {
xAxes: [{
type: 'linear'
}]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Chart.js showing nothing on canvas

I'm trying to create a graphic in my .html file in the altervista ftp.
Here's my code:
<canvas id="myChart" width="400" height="200"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js" />
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
...
],
borderColor: [
'rgba(255,99,132,1)',
...
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
Why I'm getting nothing in canvas?
Also the console does not show errors.
You should remove the ... under backgroundColor and borderColor or add colors according to the number of labels.
You need to call myChart.update() after initializing the chart.
I solved my error editing the first script from this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js" />
to this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js" ></script>
as suggested by #j.ian.le
And adding
responsive: false,
under options: {

Tick label overlaps axis label

ChartJS v2
I am having a problem on small screen sizes (using the iPhone 5 screen emulator in Chrome) with my X axis tick labels overlapping my X axis label.
My Y axis label is also being cut off.
I have tried playing around with padding and lineHeight for Label 2 to no avail. I have also tried setting the max / min rotation values for the X axis tick labels to 90deg which makes the issue worse.
The example in the screenshot above uses these settings:
var ctx = document.getElementById("myChart").getContext("2d");
var chart = new Chart(ctx, {
// The type of chart we want to create
type: "bar",
// The data for our dataset
data: {
labels: [
"0k-40k",
"40k-80k",
"80k-100k",
"100k-120k",
"120k-160k",
"160k-180k",
"180k-220k"
],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: [0, 10, 5, 2, 20, 30, 45]
}
]
},
// Configuration options go here
options: {
legend: {
display: false
},
scales: {
xAxes: [
{
ticks: {
autoSkip: false,
fontSize: 16,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
},
scaleLabel: {
display: true,
fontSize: 16,
fontStyle: "bold",
labelString: "Chart Label X",
}
}
],
yAxes: [
{
ticks: {
fontSize: 16,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
},
scaleLabel: {
display: true,
fontSize: 16,
fontStyle: "bold",
labelString: "Chart Label Y",
}
}
]
}
}
});
This looks like it is probably a bug in ChartJS not calculating the label heights correctly when rotated. Has anybody else had this problem? Is there a work around?
Codepen: https://codepen.io/afisher88/pen/mayvoe
GitHub Issue: https://github.com/chartjs/Chart.js/issues/5906
In the end I had to compromise and shrink the font size, removing the x and y labels and updating the legend to provide the detail needed.
var ctx = document.getElementById("myChart").getContext("2d");
var chart = new Chart(ctx, {
// The type of chart we want to create
type: "bar",
// The data for our dataset
data: {
labels: [
"0k-40k",
"40k-80k",
"80k-100k",
"100k-120k",
"120k-160k",
"160k-180k",
"180k-220k"
],
datasets: [
{
label: "My dataset x vs y",
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: [0, 10, 5, 2, 20, 30, 45]
}
]
},
// Configuration options go here
options: {
legend: {
display: true
},
scales: {
xAxes: [
{
ticks: {
autoSkip: false,
fontSize: 11,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
}
}
],
yAxes: [
{
ticks: {
fontSize: 11,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
}
}
]
}
}
});
https://codepen.io/afisher88/pen/XoNVNe
Different browsers can render the canvas image in many different ways. Small screen devices are not an exception. You can try your code with different browsers on normal screen to assert your claim.
Chart.js have many options you can use for your code. i.e. You can use “Chart.bundle.js” or “Chart.js” depending on your environment. The CSS you use can also affect how your chart is rendered on a canvas. The bundled build includes Moment.js in a single file. You should use this version if you require time axes and want to include single file.
For example:
<!DOCTYPE html>
<!--
pcharts.html
-->
<html>
<head>
<title>P Charts</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../public/css/main.css">
<script src="../lib/charts/Chart.bundle.js"></script>
<script src="../lib/jquery/jquery.js"></script>
<script src="../js/appcharts.js"></script>
</head>
<body>
<h1>Charts</h1>
<hr>
<br>
<div id="myCan">
<canvas id="myChart" width="100" height="100"></canvas>
</div>
<br>
<br><br><hr><br><br>
</body>
</html>
appcharts.js
/*
* appcharts.js
*
*/
var ctx;
var myChart;
var cdata = [0, 10, 5, 2, 20, 30, 45];
var lblX = ["0k-40k","40k-80k","80k-100k","100k-120k","120k-160k","160k-180k","180k-220k"];
function init(){
render();
};
function render(){
ctx = document.getElementById("myChart").getContext('2d');
myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lblX,
datasets: [{
label: 'My demo2 dataset.',
data: cdata,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
ticks:{
beginAtZero:true
},
scaleLabel:{
display: true,
labelString: "Chart Label X."
}
}],
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true,
labelString: "Chart Label Y."
}
}]
}
}
});
};
//
//$(document).ready(function(){
// $("#myCan").hide("slow");
// $("#myCan").show("slow");
//});
//
window.onload = function(){
init();
};
//
//
Squeezing the big image in a small canvas is like squeezing big tomatoes in a small bottle. What will come out of that bottle is the tomato sauce and tomato seeds. Of course you can replant the tomato seeds if only and only if they are still OK. Orthographic projection do just that. You can render a big
image in a small screen by using orthographic projection technique. e.g. Positioning of the camera or distortion determines what the viewer will see or look at.
When you are using charts you are actually drawing an image and rendering it on a screen for the viewer to look at. You can get the latest version of chart.js by using: npm install chart.js --save or download it from: https://github.com/chartjs/Chart.js/releases/latest It comes with docs and samples.
To create a chart, we need to instantiate the Chart class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart. Once you have the element or context, you're ready to instantiate a pre-defined chart-type or create your own.
Good luck.

error : "Uncaught TypeError: Cannot read property 'length' of null" Chart.js

I made several graphic with Chart.js that works. But the polar graphic and the radar does not work. I get the following error : "Uncaught TypeError: Cannot read property 'length' of null"
I use charjs 2.3.0
I do not understand where the error can come .
<div class="col-lg-6 col-md-6">
<canvas class="box box-warning" id="myChart4" width="400" height="400"></canvas>
</div>
<div class="col-lg-6 col-md-6">
<canvas class="box box-warning" id="myChart5" width="400" height="400"></canvas>
</div>
//////////////////////////////////////////////
// Chart Polar
//////////////////////////////////////////////
var ctx = document.getElementById("myChart4");
new Chart(ctx, {
type: 'polarArea',
data: {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
},
options: {
cutoutPercentage: 50,
animation: {
animateScale: false
}
}
});
//////////////////////////////////////////////
// Radar
//////////////////////////////////////////////
var ctx = document.getElementById("myChart5");
var scatterChart = new Chart(ctx, {
type: 'radar',
data: data = {
labels: ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche", ],
datasets: [{
label: 'the first dataset',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
data: [10, 34, 50, 34, 56, 65, 43]
}, {
label: 'the second dataset',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
data: [54, 72, 100, 36, 76, 23, 21]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
the problem is this line:
var ctx = document.getElementById('sexe');
you do not have any element with id "sexe" on the page
The error was due to the element not being present in the HTML when Chart.js was trying to attach the chart on it.
If u are using Angular 2+, try to build the options and data chart in. I needed to do this because I used an #Input() attribute to get the data shown in the chart:
ngOnChanges(changes: SimpleChanges){
this.options = {
responsive: true,
maintainAspectRatio: false,
...
}
}
That's works for me. Hope it helps someone.

Filling area between two lines - Chart.js v2

I am trying to fill the area between two lines in a line chart using Chart.js. Like this:
There is already an answer here, that explains how to extend chartjs to do this.
But I know this feature is now native in V2 (from this thread on the github issues page), the problem is I just can't find documentation referring to this.
Is there a section about this in the doc? Anyone know how to use this feature?
Thanks!
Make sure you import the 2.6.0 version:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
Then follow the rules as described here: http://www.chartjs.org/docs/latest/charts/area.html
Below is an example, and how it looks:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My two lines with colour between them</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</head>
<body>
<canvas id="mychart" width="300" height="200"></canvas>
<script>
var ctx = document.getElementById('mychart').getContext('2d'); //get the context (canvas)
var config = { //configure the chart
type: 'line',
data: {
labels: [1, 2, 3, 4],
datasets: [{
label: "Min",
backgroundColor: 'rgba(55, 173, 221, 0.6)',
borderColor: 'rgba(55, 173, 221, 1.0)',
fill: false, //no fill here
data: [5, 5, 3, 2]
},
{
label: "Max",
backgroundColor: 'rgba(55, 173, 221, 0.6)',
borderColor: 'rgba(55, 173, 221, 1.0)',
fill: '-1', //fill until previous dataset
data: [8, 7, 6, 5]
}]
},
options: {
maintainAspectRatio: false,
spanGaps: false,
elements: {
line: {
tension: 0.000001
}
},
plugins: {
filler: {
propagate: false
}
},
scales: {
xAxes: [{
ticks: {
autoSkip: false
}
}]
}
}
};
var chart = new Chart(ctx, config);
</script>
</body>
</html>
Setting fill property to +1 of a dataset will set the backgroundColor from this line to the next line in dataset.
datasets: [{
label: 'Systolic Guideline',
data: [],
fill: '+1',
borderColor: '#FFC108',
backgroundColor: 'rgba(255,193,8,0.2)'
},
{
label: 'Diastolic Guideline',
data: [],
fill: true,
borderColor: '#FFC108',
backgroundColor: 'rgba(0,0,0,0)'
}]
See this: https://www.chartjs.org/samples/latest/charts/area/line-datasets.html
Here is a small plugin that can do shading between any two dataset lines.
https://stackoverflow.com/a/41733045/852977

Categories

Resources