Chartsjs only showing two data points - javascript

I am using charts.js to visualise some data, but unfortunately, I only see two data points, while the scale is like to highest value.
This is my code.
<canvas id="myChart" width="400" height="80"></canvas>
<script>
window.onload=function() {
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: '',
datasets: [{
label: 'Tests',
backgroundColor: 'rgb(252, 160, 12)',
borderColor: 'rgb(8, 19, 42)',
data: [
{x:'2016-12-23', y:200}, {x:'2016-12-24', y:300}, {x:'2016-12-25', y:400}, {x:'2016-12-26', y:100}
]
}]
},
// Configuration options go here
options: {
legend: {
display: false
},
}
});
};
</script>
I don't see, why this is limited. Suggestions are more than welcome.

Try like this, please.
<canvas id="myChart" width="400" height="80"></canvas>
<script>
window.onload=function() {
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['2016-12-23','2016-12-24','2016-12-25','2016-12-26']
datasets: [{
label: 'Tests',
backgroundColor: 'rgb(252, 160, 12)',
borderColor: 'rgb(8, 19, 42)',
data: [200, 300, 400 100]
}]
},
// Configuration options go here
options: {
legend: {
display: false
},
}
});
};
</script>

Related

How to set action on slice-click Doughnut in Chart.js

I've been trying to add chart.js to my Django Project, which worked pretty fine so far. I made a doughnut-chart with two slices. Now i want to have each of those slices to have seperate actions on click, like for example redirecting to new side.
These are my chart settings:
var config = {
type: 'doughnut',
data: {
datasets: [{
data: {{ data|safe }}, // Error because django and js are being mixed
backgroundColor: [
'#ff0000', '#008000'
],
label: 'Population'
}],
labels: {{ labels|safe }}
},
options: {
responsive: true
}
};
And this is the rendering and my function to make the actions on click:
window.onload = function() {
var ctx = document.getElementById('pie-chart').getContext('2d');
var myPieChart = new Chart(ctx, config);
$('#myChart').on('click', function(event) {
var activePoints = myPieChart.getElementsAtEvent(event)
if(activePoints[0]){
console.log("Helo 1")
}
else {
console.log("helo 2")
}
})
};
I saw my solution on other pages, but it doesn't work at all. Am I missing something? If yes could you please help?
getElementAtEvent has been replaced with chart.getElementsAtEventForMode in Chart.js v3 (see 3.x Migration Guide).
Please take a look at below runnable code and see how it works now:
const pieChart = new Chart("myChart", {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
data: [8, 5, 6],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
}]
},
options: {
onClick: evt => {
var elements = pieChart.getElementsAtEventForMode(evt, 'index', { intersect: true }, false);
var index = elements[0].index;
console.log(pieChart.data.labels[index] + ': ' + pieChart.data.datasets[0].data[index]);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

Counting string to plot a graph using chart.js and angular

I am trying to create a bar chart in angular using chart.js and angular.
I want to display the disaters vs area. with the type of disaster ( earthquake, hurricane, storm...etc) on the x-axis and area (as in location) on the y-axis.
However, the area data is string and does not work when trying to plot a bar graph as it requires numbers.
I am reading the data as follows:
ngOnInit(): void {
this.chartService.noOfEqu().subscribe((res) => {
let area = res.map((res) => res.area);
let disaster = res.map((res) => res.disasterNature);
new Chart('disasterCanvas', {
type: 'bar',
data: {
labels: disaster,
datasets: [
{
data: area,
label: 'area',
backgroundColor: '#A121D5',
},
],
},
options: {
plugins: {
legend: {
display: true,
},
},
scales: {
x: {
ticks: {
display: true,
},
},
y: {
ticks: {
display: true,
},
},
},
},
});
});
}
}
Where let area = res.map((res) => res.area); is the area variable.
I want to know what is the best way to structure the data to be entered into the graph.
The disaster data that is logged is:
and the area data :
How can i structure the area such that it counts how much areas that a disaster has occured and plot it on the bar chart?
Thank you in advance...if there is anything i can clarify please let me know in the comments
Also is there another way to display this data besides tallying the string data?
You need to add a labels array to the scale and set the type to category to use string data:
const options = {
type: 'bar',
data: {
labels: ["Earthquake", "Tornade", "Flood"],
datasets: [{
label: '# of Votes',
data: ['Paris', 'Berlin', 'London'],
backgroundColor: 'pink'
}]
},
options: {
scales: {
y: {
type: 'category',
reverse: true,
labels: ['', 'London', 'Paris', 'Berlin']
}
}
}
}
const 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/3.7.1/chart.js"></script>
</body>

How can I display the xAxes and yAxes data in the tooltip, Chart JS?

I am trying to achieve the Tooltip shown below in the first image. Inside of the tooltip I need to display the yAxes and xAxes data. The chart.js version I am using is 3.7.0
My tooltip looks like this:
The tooltip that I am trying copy:
The chart.js documentation is quite hard for me to understand. Is there any guru that can explain to me.
Question: Why is my tooltip returning the yAxes data, that I return as a variable(label) as undefined?
Are there any other options I can use to make my chart look like the chart in the second picture?
My Code:
tooltip: {
displayColors: false,
backgroundColor: 'rgba(45,132,180,0.8)',
bodyFontColor: 'rgb(255,255,255)',
callbacks: {
title: function(item, everything){
return;
},
label: function(item, everything){
//console.log(item);
//console.log(everything);
let first = item.yLabel;
let second = item.xLabel;
let label = first + ' ppm';
return label;
}
}
}
Thank you in advance for your time and efforts, please help me figure out what am I doing wrong!
yLabel and xLabel dont exist anymore on the tooltip, they are V2 syntax.
You can just axess the y object in the parsed section to get the y value. Then you can use the afterBody callback to show the x label like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
plugins: {
tooltip: {
displayColors: false,
backgroundColor: 'rgba(45,132,180,0.8)',
bodyFontColor: 'rgb(255,255,255)',
callbacks: {
title: () => {
return
},
label: (ttItem) => (`${ttItem.parsed.y} ppm`),
afterBody: (ttItems) => (ttItems[0].label)
}
}
}
}
}
const 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/3.7.0/chart.js"></script>
</body>

chart.js - how to draw and manage line when only one label present in chart js Linechart

I'm using Chart.JS v 2.9.3 to create a line chart
line-chart diagram to show the month-wise total of expenses of selected product
For example, if the user select XYZ product then this charts would show the monthly expenses [Jan-2021-Dec-2021]
and if that respective product expense only present Jan-2021 then it displays month on y-Axes at staring
here is jsfiddle example
Adding offset trick I had already tried xAxes : [{ offset:true }],
var config = {
type: 'line',
data: {
labels: ["jan-2021"],
datasets: [{
label: "month-year",
data: [65],
backgroundColor: "rgb(118, 101, 228)",
}],
},
scales : {
xAxes : [{
offset:true
}],
},
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<div class="myChart">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
</div>
please refer to the above image for getting an idea of what I'm trying to archive, I'm not concern about dot that on the chart
As you can see, the points are stick to the y-axis. Is there a possibility to center the line chart when only one data is present in the diagram?
Chart.js does not support this kind of use case since it gives a distorted image of your chart since point and label don't align anymore. If you really want this you can check beforehand in your code if there is only 1 data point there. If this is the case add an empty string in your labels array in the front and back and add zero at the front of back of your data array (or a slightly lower value as your single datapoint so that the scales don't get big steps) like so:
var config = {
type: 'line',
data: {
labels: ["", "January-2021", ""],
datasets: [{
label: "month-year",
data: [0, 134335066, 0],
backgroundColor: "rgb(118, 101, 228)",
}],
},
scales: {},
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<div class="myChart">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>
</div>
You can use align option:
var mybarChart = new Chart(ctx, {
type: 'bar',
responsive: true,
data: data,
options: {
legend: {
display: false,
position: 'bottom',
align: 'center'
},
var config = {
type: 'line',
data: {
labels: ["", "January-2021", ""],
datasets: [{
label: "month-year",
data: [0, 134335066, 0],
backgroundColor: "rgb(118, 101, 228)",
}],
options: {
legend: {
display: false,
position: 'bottom',
align: 'center'
},
},
scales: {},
};
refer to this

Chartjs Nested Doughnut Layers With Different Thickness

How can I create a nested doughnut that has layers with different thickness? Chartjs only allows cutoutPercentage to be defined in options property and all layers are changed by this value. I want to have a nested doughnut that has layers with different thickness. For example, in this chart, I want to make red and blue layers with different thickness.
var ctx = document.getElementById("chart");
var chart = new Chart(ctx, {
type: 'doughnut',
options: {
cutoutPercentage: 75
},
data: {
datasets: [{
backgroundColor: [
"red"
],
data: [1]
},
{
backgroundColor: [
"blue"
],
data: [1]
}
]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<canvas id="chart"></canvas>
I have found the solution by putting two doughnut charts on top of each other. In this way, I was able to set different cutoutPercentage values. In this example, red and blue layers have different thickness.
var ctx = document.getElementById("chart");
var chart = new Chart(ctx, {
type: 'doughnut',
options: {
cutoutPercentage: 20
},
data: {
datasets: [{
backgroundColor: [
"red"
],
data: [1]
}]
}
});
var ctx2 = document.getElementById("chart2");
var chart2 = new Chart(ctx2, {
type: 'doughnut',
options: {
cutoutPercentage: 90
},
data: {
datasets: [{
backgroundColor: [
"blue"
],
data: [1]
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<div class="container" style="position:relative; ">
<canvas id="chart" style="position:absolute;"></canvas>
<canvas id="chart2" style="position:absolute;"></canvas>
</div>

Categories

Resources