How to show multiple datasets in line chart js - php

I'm using line chart.js
I want to show my line chart have two line (actually it's will dynamic datasets)
base with location and label in bottom will base with month.
Now my chart it's show only last data set.
My data is look like this
{
location: "Apartment A",
color: "#b168ac",
set_data: [{
month: 1,
value: 3500
},{
month: 2,
value: 2700
},{
month: 3,
value: 1500
}]
},
{
location: "Apartment B",
color: "#b168aa",
set_data: [{
month: 1,
value: 1700
},{
month: 2,
value: 2800
},{
month: 3,
value: 3200
}]
}
I made my code something like this:
var obj = JSON.parse(data);
$.each(obj,function(i,item){
var locate = [];
var amt = [];
var color = [];
var item_set = [];
locate.push(item.location);
var m = [];
var val = [];
var item_s = item.set_data;
$.each(item_s,function(i2,item2){
val.push(item2.value);
m.push(item2.month);
var chartdata = {
labels: m,
datasets : [{
label:locate,
data: val,
backgroundColor: item.color,
borderWidth: 1,
fill: false,
}]
};
var ctx = document.getElementById("graph_by_usage").getContext('2d');
var LineChart = new Chart(ctx,{
type : 'line',
data : chartdata,
options: {
responsive:true
}
});
});
});
The data should be look like this https://codepen.io/k3no/pen/pbYGVa
Please advice me. Thank you.

Assuming that your data is a JSON array, you could generate labels and datasets as follows:
const labels = baseData[0].set_data.map(v => v.month);
const dataSets = [];
baseData.forEach(o => dataSets.push({
label: o.location,
data: o.set_data.map(v => v.value),
borderColor: o.color,
borderWidth: 1,
fill: false
})
);
Please have a look at the runnable code sample below.
const baseData = [{
location: "Apartment A",
color: "red",
set_data: [
{ month: 1, value: 3500 },
{ month: 2, value: 2700 },
{ month: 3, value: 1500 }
]
},
{
location: "Apartment B",
color: "blue",
set_data: [
{ month: 1, value: 1700 },
{ month: 2, value: 2800 },
{ month: 3, value: 3200 }
]
}
];
const labels = baseData[0].set_data.map(v => v.month);
const dataSets = [];
baseData.forEach(o => dataSets.push({
label: o.location,
data: o.set_data.map(v => v.value),
borderColor: o.color,
borderWidth: 1,
fill: false
})
);
new Chart('graph_by_usage', {
type : 'line',
data: {
labels: labels,
datasets: dataSets
},
options: {
responsive:true
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="graph_by_usage" height="90"></canvas>

Related

Chartjs.org Displaying different data on Radar Chart tooltip

For example, on the tooltip, I want to show the data for option1 not 2 but 200. Because we show adapted data in the graph. But it will be better to show the real data on the tooltip.
<script>
new Chart(document.getElementById('exampleChartjsRadar').getContext('2d'), {
type: 'radar',
data: {
labels: ["Option1", "Option2", "Option3"],
pointLabelFontSize: 14,
datasets: [{
label: 'Sporcu',
data: [2, 4, 5],
fill: true,
backgroundColor: 'rgba(4, 197, 249, 0.2)',
borderColor: 'rgb(4, 197, 249)',
pointBackgroundColor: 'rgb(4, 197, 249)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(4, 197, 249)'
}]
},
options: {
plugins: {
},
elements: {
line: {
borderWidth: 2
}
}
},
});
</script>
enter image description here
You can use the tooltip callback for this:
const options = {
type: 'radar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: (ctx) => (`${ctx.dataset.label}: ${ctx.raw *100}`)
}
}
}
}
}
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.8.0/chart.js"></script>
</body>
Thanks for the answer, how can I use it if I want to write different values instead of multiplying by 100.
label: (ctx) => (`${ctx.dataset.label}: ${ctx.raw *100}`)

How to set php data to chart.js for creating graph?

my json data looks like this
[
{"records":"3","month":"Jan"},
{"records":"6","month":"Feb"},
{"records":"2","month":"Mar"},
]
Now, how to show this data inside graph. I am using chart.js.
new Chart(document.getElementById("bar-chart-data"), {
type: 'bar',
data: {
labels: 'set the labels here',
datasets: [
{
label: "set the month name here",
data: [set the records data here]
}
]
},
options: {
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
stepSize: 10,
beginAtZero: true,
},
}]
},
}
});
I also look many example of this. But, not able to understand. Is there an better way to achieve this? Any Example to solve this?
Unfortunately I don't know much about php. But since you haven't received an answer yet, I can explain the part related to Chart.js.
Given your data already present in an array, which I named jsonData, you can use the Array.map() method to extract labels and data as follows:
labels: jsonData.map(o => o.month),
datasets: [{
label: "Records per Month",
data: jsonData.map(o => o.records),
Please have a look at your amended and runnable code below:
const jsonData = [
{"records":"3","month":"Jan"},
{"records":"6","month":"Feb"},
{"records":"2","month":"Mar"},
];
new Chart(document.getElementById("bar-chart-data"), {
type: 'bar',
data: {
labels: jsonData.map(o => o.month),
datasets: [{
label: "Records per Month",
data: jsonData.map(o => o.records),
backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)"],
borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)"],
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
stepSize: 10,
beginAtZero: true,
},
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="bar-chart-data" height="90"></canvas>

Show multiple data in a single data in chart.js

I have design a simple graph with chart.js, Which looking cool.
But now i want to show their data between one Month to another Month.
Means their are following data:
1th january, 2017 : 12
3rd January, 2017: 16
And so on..
now i want to show their January to February data as image,which is shown below:
Here is my simple code
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: ["January 2017", "February 2017", "March 2017", "April 2017", "May 2017", "June 2017", "July 2017"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132,0.25)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 15],
lineTension:0
}]
},
// Configuration options go here
options: {}
});
jsfiddle Here : https://jsfiddle.net/2qxj9t00/2/
I've google so many times but no any solution are their, so kindly suggest me. Thanks :)
You can accomplish this using the following x-axis ticks callback function ...
ticks: {
callback: function(e) {
var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
if (tick != aR) {
aR = tick;
return tick;
}
}
}
assuming your labels array would look somewhat like this.. ["1st January 2017", "3rd January 2017", "4th February 2017", ...]
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
var aR = null; //store already returned tick
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ["1st January 2017", "3rd January 2017", "4th February 2017", "9th February 2017", "3rd March 2017", "15th March 2017"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgb(255, 99, 132)',
data: [12, 16, 10, 11, 9, 15],
lineTension: 0
}]
},
options: {
scales: {
xAxes: [{
ticks: {
autoSkip: false,
callback: function(e) {
var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
if (tick != aR) {
aR = tick;
return tick;
}
}
}
}],
yAxes: [{
ticks: {
min: 0,
max: 30
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>

Highcharts Column Chart Not Displaying Dynamic Values

Hi I need to create one dynamic column chart. But i am not able to put my values to the data field of value how can i do that
function getusercategorygraph()
{
$.getJSON('config/alumniusermodes.php',function(data){
// Create a new array
var finaldata = [];
var chart;
// Perform your operations
$.each(data, function( index, value ) {
// Create a new hash
var currentItem = {}
// Create the proper values in your hash
$.each(value, function( index, value ) {
currentItem[index] = value;
});
finaldata += currentItem;
});
var chart = new Highcharts.Chart({
chart: {
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
//type: 'category',
categories: []
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
//data: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
//data: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
data : finaldata,
}],
});
});
}
But the graph doesnt show anything. Whats wrong in this code. Please help.
this is the result from api that i got
[{"name":"Standard","y":"52"},{"name":"Silver","y":"24"},{"name":"Gold","y":"20"},{"name":"Platinum","y":"6"}]
Thanks in Advance
To get you started, on line 18, change
finaldata += currentItem;
to
finaldata.push({
name: currentItem.name,
y: parseFloat(currentItem.y)
});
See JSFilddle.
Edit: Used suggestions by Sebastian in comments. Thanks!
Here is the working version keeping the highchart code inside $.getJSON callback function.
I added following PHP back-end code to get highchart sample data.
$data[] = array('name' => 'Standard', 'y'=> 52);
$data[] = array('name' => 'Silver', 'y'=> 24);
$data[] = array('name' => 'Gold', 'y'=> 20);
$data[] = array('name' => 'Platinum', 'y'=> 6);
echo json_encode($data);
exit;
This data is nothing but giving me data to use in highchart. Following is the javascript call to get it functional.
getusercategorygraph();
function getusercategorygraph()
{
$.getJSON('http://<mydomain>/getdata.php',function(data){
var chart = new Highcharts.Chart({
chart: {
renderTo : 'container',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
//type: 'category',
categories: []
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat:'<span style="color:{point.color}">{point.name}</span>:<b>{point.y}Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
data: data
}],
});
});
}

High charts using candlestick,vloum and MACD

I am new to highcharts and i am using hightcharts graph but volume not showing.When i remove MACD then volume show i don't understand why i am getting this issue!. my code are
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
var ohlc = [],
volume = [],
dataLength = data.length;
for (i = 0; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
volume.push([
data[i][0], // the date
data[i][5] // the volume
])
}
// set the allowed units for data grouping
var groupingUnits = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function() {
$('#container').highcharts('StockChart', {
title : {
text : 'MACD of AAPL stock price'
},
subtitle: {
text: 'From may 15, 2006 to May 10, 2013'
},
yAxis: [{
title: {
text: 'Price'
},
height: 200,
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
}, {
title: {
text: 'MACD'
},
top: 320,
height: 100,
offset: 0,
lineWidth: 2
}, {
title: {
text: 'Volume'
},
top: 500,
height: 60,
offset: 0,
lineWidth: 2
}],
tooltip: {
crosshairs: true,
shared: true
},
rangeSelector : {
selected : 1
},
legend: {
enabled: true,
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
plotOptions: {
series: {
marker: {
enabled: false,
}
}
},
series : [{
name: 'AAPL Stock Price',
type : 'line',
id: 'primary',
data : data
}, {
name : 'MACD',
linkedTo: 'primary',
yAxis: 1,
showInLegend: true,
type: 'trendline',
algorithm: 'MACD'
}, {
type: 'candlestick',
name: 'AAPL',
data: ohlc,
dataGrouping: {
units: groupingUnits
}
}, {
type: 'column',
name: 'Volume',
linkedTo: 'primary',
data: volume,
yAxis: 1,
dataGrouping: {
units: groupingUnits
}
}, {
name: 'Histogram',
linkedTo: 'primary',
yAxis: 1,
showInLegend: true,
type: 'histogram'
}]
});
});
});
Why volume is not showing?
Thanks in advance!
You have three yAxis, but in each serie (except first) you use yAxis:1 which means that series is displayed on that axis. So you need to modify axis index to display on the "last" yAxis.

Categories