I'm trying to visualize the following dataset with chart.js
var data =
{
"count": 2,
"result": {
"2020-01-22": {
"confirmed": 12,
"deaths": 5,
"recovered": 4
},
"2020-01-23": {
"confirmed": 20,
"deaths": 3,
"recovered": 2
}
}
}
So far I've figured out how to use the dates as label.
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
data: { // mapping the dates as labels
labels: Object.entries(data.result).map( (item) => item[0]),
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: ??
},{
label: 'My Second dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: ??
},{
label: 'My Third dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: ??
}]
}, // Configuration options go here
options: {}
});
I'd like to display the values of 'confirmed', 'deaths' and 'recovered' as three lines within this chart. Therefore I would include three different datasets right? How would I access the required information from json as array to populate the data arrays?
Thanks for your support
just map the key and values to appropriate arrays and consume them as datasets and labels.
var data = {
"count": 2,
"result": {
"2020-01-22": {
"confirmed": 12,
"deaths": 5,
"recovered": 4
},
"2020-01-23": {
"confirmed": 20,
"deaths": 3,
"recovered": 2
}
}
}
var dates = Object.keys(data["result"]).map(x => x);
var confirm = Object.values(data.result).map(x => x.confirmed);
var deaths = Object.values(data.result).map(x => x.deaths);
var recovered = Object.values(data.result).map(x => x.recovered);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: dates,
datasets: [{
label: 'confirmed',
data: confirm,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
},
{
label: 'Deaths',
data: deaths,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}, {
label: 'recovered',
data: recovered,
backgroundColor: 'rgba(255, 206, 86, 0.2)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="100" height="50"></canvas>
Related
I have a pie chart and I want to get the number/data of each section of pie chart when hovered upon. I have seen the implementation of this in version 2.9.x but in version 3.x it is not working. I have also tried doing this here:
var pieChartHome = new Chart(
"myChart",
{
type: 'doughnut',
data: {
labels: ['One', 'Two', 'Three'],
datasets: [{
data: [4, 5, 3],
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
borderWidth: 1,
hoverBorderWidth: 3
}]
},
options: {
responsive:false,
plugins: {
legend: {
position:'right',
onHover: (evt, legendItem,legend) => {
const index = pieChartHome.data.labels.indexOf(legendItem.text);
const rect = pieChartHome.canvas.getBoundingClientRect();
const point = pieChartHome.getDatasetMeta(0).data[index].getCenterPoint();
const e = new MouseEvent('mousemove', {
clientX: rect.left + point.x,
clientY: rect.top + point.y
});
pieChartHome.canvas.dispatchEvent(e);
},
}
}
},
}
);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
But this shows me flickering data and not something like this:
Chart.js - show tooltip when hovering on legend
You can set the tooltip via chart.js public methods itself:
var options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
legend: {
position: 'left',
onHover: (evt, item, legend) => {
const chart = legend.chart;
const tooltip = chart.tooltip;
const chartArea = chart.chartArea;
tooltip.setActiveElements([{
datasetIndex: 0,
index: item.index,
}], {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
chart.update();
},
}
}
}
}
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/3.4.1/chart.js"></script>
</body>
I created this piechart using chartsjs. As of now, if you run the snippet, I am able to display my labels the following way:
Uno\Company 1
19
(56%)
However, I would love to display Company text underneath, so that it can be displayed like this:
Uno
Company1
19
(56%)
I tried creating a separate array: label2: ["Company1", "Company2", "Company3"]
Then in the callback, I added a new function, which i thought would give me the other label beneath, but no luck. Here is the code I used for that:
title2: function(tooltipItem, data, label2){
return data['label2'][tooltipItem[0]['index']]
}
Can anyone help me out?
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
label1: ["Uno\\Company1", "Dos\\Company2", "Tres\\Company3"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
tooltips: {
callbacks: {
title: function(tooltipItem, data, label1, label2) {
return data ['label1'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']];
},
afterLabel: function(tooltipItem, data) {
var dataset = data['datasets'][0];
var percent = Math.round((dataset['data'][tooltipItem['index']] / dataset["_meta"][0]['total']) * 100)
return '(' + percent + '%)';
}
},
backgroundColor: '#FFF',
titleFontSize: 16,
titleFontColor: '#0066ff',
bodyFontColor: '#000',
bodyFontSize: 14,
displayColors: false
}
}
});
<div>
<canvas id="myChart" height="100"></canvas>
<div id="chartjs-tooltip">
<table></table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js">
</script>
Simply change label1 from an array of strings to an array of arrays:
label1: [["Uno", "Company1"], ["Dos", "Company2"], ["Tres", "Company3"]]
Chart.js will treat separate array items as separate lines.
I try to create a website with a bar-chart on it. I like to use ChartJs.
There are some good examples, but I don't know how to visualise the data if the data is an array.
var myArray = [{
year: '2016',
value: 5
},
{
year: '2017',
value: 9
},
{
year: '2018',
value: 4
}
];
How do I loop throu myArray to create a bar chart like this one in the example?
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['2016', '2017', '2018'],
datasets: [{
label: '# of Votes',
data: [5, 9, 4],
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: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Thanks for your help!
Best, Marius
You can map your array of objects, getting only the value you need.
I did it by var values = myArray.map((x) => x.value) and then using values as the value to the data property inside chart options.
For the labels, you can use the same logic, but with x.year.
Below code represents an example:
var myArray = [{
year: '2016',
value: 5
},
{
year: '2017',
value: 9
},
{
year: '2018',
value: 4
}
];
//FILTER THE VALUES
var values = myArray.map((x) => x.value)
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['2016', '2017', '2018'],
datasets: [{
label: '# of Votes',
data: values,
borderWidth: 1,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="300" height="150"></canvas>
If, for some reason (browser maybe), you cant use arrow functions, then go with:
var values = myArray.map(function(x) {return x.value})
I have a pie chart made with chart.js and currently i'm wondering if its possible to only have a border for the outside of the circle / arc like so:
I tried the following configurations but it applies border the to the whole segment.
options: {
elements: {
arc: {
borderWidth: 0
}
}
}
and also:
data: {
datasets: [{
data: [male_data , female_data],
backgroundColor: pieColors1,
borderWidth: [10, 0, 0, 0, 0]
}]
},
but this is what im getting:
I guess you have to create your own color image (Solid color with white strip on top) and pass it in as a canvas image.
Below is a modified example I've made based on the sample given from the chart.js documentation and a random picture found on the net.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0/Chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var img = new Image();
img.src = 'http://www.worktop-express.co.uk/media/gbu0/metro-tiles-white-sparkle-worktops-100717.jpg';
img.onload = function() {
var ctx = document.getElementById("myChart").getContext('2d');
var fillPattern = ctx.createPattern(img, 'repeat');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 10)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
fillPattern
],
borderColor: [
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)'
],
borderWidth: 0
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0/Chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var img = new Image();
img.src = 'http://www.worktop-express.co.uk/media/gbu0/metro-tiles-white-sparkle-worktops-100717.jpg';
img.onload = function() {
var ctx = document.getElementById("myChart").getContext('2d');
var fillPattern = ctx.createPattern(img, 'repeat');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 10)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
fillPattern
],
borderColor: [
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)',
'rgba(0,0,0,100)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
Good evening,
I'm trying to build a line chart that represents API response time. The problem is that I didn't find any solution in Chart.JS documentation. Is there any native solution or any solution using canvas api?
I want to get the chart looking like this:
Here is the code that I've used to generate the chart
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: hoursArrFirst,
datasets: [{
label: 'First Brand API',
data: timeArrProftit,
borderWidth: 1,
backgroundColor: [
'rgba(255, 99, 132, 0.05)',
'rgba(255, 159, 64, 0.05)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(255, 59, 64, 1)'
]
},{
label: 'Second Brand API',
data: timeArrSecond,
borderWidth: 1,
backgroundColor: [
'rgba(132, 255, 99, 0.05)',
'rgba(64, 255, 159, 0.05)'
],
borderColor: [
'rgba(32,155,99,1)',
'rgba(64,155, 59, 1)'
]
},{
label: 'Third Brand API' ,
data: timeArrThird,
borderWidth: 1,
backgroundColor: [
'rgba(32, 99, 255, 0.05)',
'rgba(64, 59, 255, 0.05)'
],
borderColor: [
'rgba(32, 99, 120, 1)',
'rgba(64, 59, 120, 1)'
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
Call a function during and after animation
var options = {
onAnimationProgress: function() { drawDatasetPointsLabels() },
onAnimationComplete: function() { drawDatasetPointsLabels() }
}
function drawDatasetPointsLabels() {
ctx.font = '.9rem sans-serif';
ctx.fillStyle = '#AAA';
ctx.textAlign="center";
$(Trends.datasets).each(function(idx,dataset){
$(dataset.points).each(function(pdx,pointinfo){
// First dataset is shifted off the scale line.
// Don't write to the canvas for the null placeholder.
if ( pointinfo.value !== null ) {
ctx.fillText(pointinfo.value,pointinfo.x,pointinfo.y - 15);
}
});
});
}