Chart.js working with database arrays and data structures - javascript

I'm making a chart which is drawing data from a database array. I have 2 arrays:
const numPostPerCat= <?php echo json_encode($countCateT); ?>;
const catName= <?php echo json_encode($cateTforChart); ?>;
Which I use to feed the chart in the traditional way:
const data2= {
labels: catName,
datasets: [{
label: 'Terri',
backgroundColor: 'rgb(166,166,166)',
borderColor: 'rgb(166,166,166)',
data: numPostPerCat,
borderWidth: 2,
barThickness: 3,
datalabels: {
color:'gray',
anchor: 'end',
align: 'top',
},
}],
};
const config2={
type: 'bar',
data: data2,
options: {
scales: {
x:{
grid:{
display: false,
},
},
y:{
ticks:{
display: false,
},
grid:{
display: false,
},
},
},
plugins:{
legend: {
display: false
},
title:{
display: true,
text: 'Territorios',
align: 'start',
},
},
responsive: true,
maintainAspectRatio: false,
}
};
const myChart2 = new Chart(
document.getElementById('myChart2'),
config2
);
But how can I use database arrays when I want to use data structure? Should I use a different kind of a array? There's another configuration in JS? because this doesn't work:
const data2= {
datasets: [{
label: 'Terri',
backgroundColor: 'rgb(166,166,166)',
borderColor: 'rgb(166,166,166)',
data: [
{Terris: catName, cuantos: {cantidad: numPostPerCat}
},
],
borderWidth: 2,
barThickness: 3,
datalabels: {
color:'gray',
anchor: 'end',
align: 'top',
},
}]
};
const config2={
type: 'bar',
data: data2,
options: {
parsing:{
xAxisKey: 'Terris',
yAxisKey: 'cuantos.cantidad',
},
scales: {
x:{
grid:{
display: false,
},
},
y:{
ticks:{
display: false,
},
grid: {
display: false,
},
},
},
plugins:{
legend: {
display: false
},
title:{
display: true,
text: 'AƱos',
align: 'start',
},
},
responsive: true,
maintainAspectRatio: false,
}
};
const myChart2 = new Chart(
document.getElementById('myChart2'),
config2
);

Related

Create a 100 percent stacked line chart with chart.js

I'm using chart.js to build my charts, but felt the need to create a stacked chart inline, but using the stacked:true property doesn't seem to work
Here is my code
var chart1 = new Chart(document.getElementById("invests2").getContext("2d"), {
type: "line",
options: {
layout: {
padding: 0
},
elements: {
point:{
radius: 0
},
},
responsive: true,
bezierCurve: false,
maintainAspectRatio: false,
scales: {
yAxes: [{
stacked:true,
display: true,
scaleLabel: {
display: true,
},
ticks: {
maxTicksLimit:100,
fontSize:12,
maxRotation: 0,
minRotation: 0
},
gridLines: {
display: false,
}
}]
}
},
data: {
labels: ['01/04/2018','01/05/2018','01/06/2018','01/07/2018','01/08/2018','01/09/2018'],
datasets: [{
type: 'line',
label: 'Tit. Publicos',
data: [20940429854.44,19639459015.81,19191914837.46,19290826114.34,19702912802,21274400792.07]
},
{
type: 'line',
label: 'Tit. Privados',
data: [315734585.11,332328878.86,349823178.63,343130519.19,342839692.62,367877901.82,]
}
]
},
});
The look presented was this
But i need this
Stacked:true not work for line chart?

Displaying labels on a Doughnut Chart using Chart.js

I am really stuck at the moment.
Using Chart.js v3.2.1 to display some charts, which were working great.
Then when I attempted use the chartjs-plugin-datalabels plugin to display labels on a Doughnut chart, that chart no longer displays.
I can't see what I've done wrong. I'm in need of help!
Note: There are a lot of questions similar to this on Google and Stackoverflow but most of them are about previous versions, but my work has only approved for me to be working with the lastst version of Chart.JS.
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [
{
label: "slices",
borderWidth: 3,
data: [2,3,2,1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}
]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2"></script>
<canvas id="canvas3-detailed"></canvas>
The link for your Plugin is broken. You need to remove #2 from the end:
https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels
There is also the not defined error because you reference ChartDataLabels which has not been declared. You need to put it in a string:
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [
{
label: "slices",
borderWidth: 3,
data: [2,3,2,1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}
]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: ["ChartDataLabels"],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="canvas3-detailed"></canvas>
I found out that the version of the plugin I used was incorrect. I have now updated and it is displaying with labels!
//DOUGHNUT GRAPH
var doughnutChartData = {
labels: [
'Dr # Fault',
'TP # Fault',
'Wthr Evt',
'Other'
],
datasets: [{
label: "slices",
borderWidth: 3,
data: [2, 3, 2, 1],
backgroundColor: [
'#D6001C',
'#00A3E0',
'#52A886',
'#2E3138'
],
borderColor: [
'#fff',
'#fff',
'#fff',
'#fff'
]
}]
};
//DOUGHNUT CHART OPTIONS
var doughnutChartOptions = {
responsive: true,
plugins: {
datalabels: {
color: 'white',
formatter: function (value, context) {
return context.chart.data.labels[
context.dataIndex
];
},
},
title: {
display: true,
text: "Reported Fault Allocation",
color: "#D6001C",
font: {
family: "AvenirNextLTW01-Regular",
size: 16,
style: 'normal'
}
},
legend: {
display: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: true
}
},
y: {
grid: {
display: true,
drawBorder: true,
},
},
},
elements: {
point: {
radius: 0
}
},
}
//DISPLAY DOUGHNUT GRAPH
var ctx = document.getElementById("canvas3-detailed").getContext("2d");
window.myDoughnut = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "doughnut",
data: doughnutChartData,
options: doughnutChartOptions
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="canvas3-detailed"></canvas>

Anyone know how to add extra comma and string to array?

i have a problem when i want to assign output into array string i already use str repace, etc but still not working..
i have output like this (in time)
$grapDate output = 09:00:0001:00:0012:00:0011:00:0010:00:0001:00:0000:00:0023:00:0022:00:00
date('H:i', strtotime($graph['Date'])
and the output become = 09:0001:0012:0011:0010:0001:0000:0023:0022:00
but i want to assign that become e.g $date = ['09:00','01:00', '12:00', etc]
because i want to use graph chart like this in my body
script type="text/javascript">
var ctx = document.getElementById('myChart2').getContext('2d');
var myChart2 = new Chart(ctx, {
type: 'line',
data: {
labels: ['$label'], //Jamnya
datasets: [{
backgroundColor: 'rgba(232,72,163,0.2)',
borderColor: '#e848a3',
label: '29 May 2020',
data: [807,657,600,578,565,576,611,855,625,573,571,584,607,647,771,943,920,647,622,608,722,832,902,1062],
fill: true,
pointRadius: 5,
pointHoverRadius: 10,
showLine: true
}]
}, options: {
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Total Online Yesterday',
position: 'top',
fontSize: 15,
fontStyle: 'bold'
},
legend: {
display: false
},
elements: {
point: {
pointStyle: 'circle'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TIME'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TOTAL ONLINE'
}
}]
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return '29 May 2020 '+data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
},
},
titleFontSize: 15,
bodyFontSize: 15,
displayColors: false
}
}
});
</script>
i still thinking how to assign parameter labels in class Chart become ['value', 'value', 'value']
First make each separate & print in JSON format.
$str = "09:0001:0012:0011:0010:0001:0000:0023:0022:00";
$date = json_encode(str_split($str, 5));

Chart.js will not show up second line

I have a question about chart.js. I created a line chart with two lines. One line for the high values and one line for the lower values.
Everything works fine, but the low red line won't appear in the diagram. Is there anything i have forgotten?
Thank you for your help!
var config = {
type: 'line',
data: {
labels: ['16:30', '17:30', '18:30', '19:30', '20:30'],
datasets: [{
label: 'High',
backgroundColor: 'blue',
borderColor: 'blue',
data: [10.43, 10.42, 10.44, 10.43, 10.40],
fill: false,
}, {
label: 'low',
fill: false,
backgroundColor: 'red',
borderColor: 'red',
data: [
[8.43, 8.5, 8.39, 8.38, 8.38],
],
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Test'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Time'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
var ctx = $('#dia');
var myChart = new Chart(ctx, config);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="dia"></canvas>
Your second dataset data array is double wrapped:
data: [
[8.43, 8.5, 8.39, 8.38, 8.38],
],
Removing the second set of brackets generates the graph correctly.
var config = {
type: 'line',
data: {
labels: ['16:30', '17:30', '18:30', '19:30', '20:30'],
datasets: [{
label: 'High',
backgroundColor: 'blue',
borderColor: 'blue',
data: [10.43, 10.42, 10.44, 10.43, 10.40],
fill: false,
}, {
label: 'low',
fill: true,
backgroundColor: 'red',
borderColor: 'red',
data: [8.43, 8.5, 8.39, 8.38, 8.38], // ****THIS IS WHERE THE UPDATE IS****
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Test'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Time'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
var ctx = $('#dia');
var myChart = new Chart(ctx, config);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="dia"></canvas>

White Space in stacked bar using chart.js

I'm using chart.js version 2.7.2 to plot some charts.
The chart is a bar chart, and i'm using a time axis to set the dataset points.
If i use a normal graph the dataset is showed correctly, but if i set the stacked axis, at the first item the render show a strange white space!
Look at the charts, with stacked:false its all ok, with stacked:true there's a strange white space at the first bar!
Is there a way to remove that white space?
Thanks
function newDate(days) {
return moment().add(days, 'd').toDate();
}
const lineData = {
labels: null,
datasets:
[
{
label: 'A',
fill: false,
backgroundColor: "hsl(50, 50%, 80%)",
data:
[
{
x: newDate(1),
y: 12
},
{
x: newDate(2),
y: 15
},
],
},
{
label: 'B',
fill: false,
backgroundColor: "hsl(250, 50%, 80%)",
data:
[
{
x: newDate(0),
y: 23
},
{
x: newDate(2),
y: 34
},
{
x: newDate(3),
y: 45
},
]
}
],
}
const lineOptions = {
type: 'bar',
data: lineData,
options:
{
title:
{
display: true,
text: 'STACKED TRUE'
},
legend:
{
display: true,
},
hover:
{
mode: 'nearest'
},
fill: false,
responsive: true,
scales:
{
xAxes:
[
{
stacked: true,
display: true,
ticks:
{
beginAtZero: false,
},
scaleLabel:
{
display: true,
labelString: "Day",
},
barThickness: 15,
type: 'time',
distribution: 'linear',
bounds: 'ticks',
time:
{
unit: 'day',
unitStepSize: 1,
displayFormats:
{
'day': 'DD/MM',
},
tooltipFormat: 'DD/MM',
}
}
],
yAxes:
[
{
ticks:
{
beginAtZero: true,
},
display: true,
stacked: true,
scaleLabel:
{
display: true,
labelString: "Items",
}
}
]
},
tooltips:
{
mode: 'x',
},
}
}
const chart = new Chart(document.getElementById("chart").getContext("2d"), lineOptions);
const lineOptions2 = {
type: 'bar',
data: lineData,
options:
{
title:
{
display: true,
text: 'STACKED FALSE'
},
legend:
{
display: true
},
hover:
{
mode: 'nearest'
},
fill: false,
responsive: true,
scales:
{
xAxes:
[
{
//stacked: true,
display: true,
ticks:
{
beginAtZero: false,
},
scaleLabel:
{
display: true,
labelString: "Day",
},
barThickness: 15,
type: 'time',
distribution: 'linear',
bounds: 'ticks',
time:
{
unit: 'day',
unitStepSize: 1,
displayFormats:
{
'day': 'DD/MM',
},
tooltipFormat: 'DD/MM',
}
}
],
yAxes:
[
{
ticks:
{
beginAtZero: true,
},
display: true,
//stacked: true,
scaleLabel:
{
display: true,
labelString: "Items",
}
}
]
},
tooltips:
{
mode: 'x',
},
}
}
const chart2 = new Chart(document.getElementById("chart2").getContext("2d"), lineOptions2);
<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>
<body>
<canvas id="chart" width="600" height="400"></canvas>
<canvas id="chart2" width="600" height="400"></canvas>
</body>
https://jsfiddle.net/tgfy6q82/42/
You have both xAxes and yAxes set to stacked:true.
Commenting out stacked:true on the yAxes will do the trick;
function newDate(days) {
return moment().add(days, 'd').toDate();
}
const lineData = {
labels: null,
datasets: [{
label: 'A',
fill: false,
backgroundColor: "hsl(50, 50%, 80%)",
data: [{
x: newDate(1),
y: 12
},
{
x: newDate(2),
y: 15
},
],
},
{
label: 'B',
fill: false,
backgroundColor: "hsl(250, 50%, 80%)",
data: [{
x: newDate(0),
y: 23
},
{
x: newDate(2),
y: 34
},
{
x: newDate(3),
y: 45
},
]
}
],
}
const lineOptions = {
type: 'bar',
data: lineData,
options: {
title: {
display: true,
text: 'STACKED TRUE'
},
legend: {
display: true,
},
hover: {
mode: 'nearest'
},
fill: false,
responsive: true,
scales: {
xAxes: [{
stacked: true,
display: true,
ticks: {
beginAtZero: false,
},
scaleLabel: {
display: true,
labelString: "Day",
},
barThickness: 15,
type: 'time',
distribution: 'linear',
bounds: 'ticks',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'DD/MM',
},
tooltipFormat: 'DD/MM',
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
},
display: true,
// stacked: true,
scaleLabel: {
display: true,
labelString: "Items",
}
}]
},
tooltips: {
mode: 'x',
},
}
}
const chart = new Chart(document.getElementById("chart").getContext("2d"), lineOptions);
<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>
<body>
<canvas id="chart" width="600" height="400"></canvas>
</body>
Alternatively, since setting yAxes stacked:true should be intended, data can be updated such that there exists data for A and B, even if one of them is 0. https://jsfiddle.net/zqrp0w76/2/

Categories

Resources