Highcharts Column Chart Not Displaying Dynamic Values - php

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
}],
});
});
}

Related

is there a way to change the date format in php?

i have a chartjs charts that display the dateformat of
'm-d-Y H:i:s'
thats how the dates come out of the sql table as, but i need them to appear as d-m-y on the charts.
my model :
class chartData extends Entity
{
public static function findBy(
\DateTime $StartDate,
\DateTime $EndDate
): array
{
$params = [
$StartDate->format('m-d-Y H:i:s'),
$EndDate->format('m-d-Y H:i:s'),
];
return self::hydrate(DB::select('EXEC Table #StartDate = ?, #EndDate = ?',
$params
));
}
}
my controller :
public function index (Request $request)
{
if (!$request->input('StartDate') && !$request->input('EndDate')) {
$StartTime = Carbon::now()->subDays(7);
$EndTime = Carbon::now();
} else {
$StartTime = Carbon::parse($request->input('StartDate'));
$EndTime = Carbon::parse($request->input('EndDate'));
}
$Activity = chartData::findBy(
Carbon::parse($StartTime),
Carbon::parse($EndTime)
);
i cant simply do a ->format('d-m-y') as i get thrown errors. does anyone have any idea of how to reformat this so the date will appear as day/month/year ?
UPDATE:
taking advise, i have changed my chartjs to include the date formatting advised:
var ctx = document.getElementById("Chart").getContext('2d');
var recentActivityChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'hours',
data: [],
barThickness: 12,
fill: true,
backgroundColor: "rgba(54, 162, 235, 1)",
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 1,
}]
},
options: {
animation: {
duration: 1000,
easing: "linear",
},
responsive: true,
maintainAspectRatio: true,
legend: {
display: false,
position: 'bottom',
usePointStyle: true,
labels: {
fontColor: "grey",
usePointStyle: true,
},
},
scales: {
yAxes: [{
gridLines: {
display: true,
borderDash: [8, 4],
},
scaleLabel: {
display: true,
labelString: 'hours',
},
ticks: {
beginAtZero: false,
}
}],
xAxes: [{
type: 'time',
time: {
parser: 'labels', // define date format that matches the php data
unit: 'day',
displayFormats: {
day: 'DD-MM-YYYY'
},
tooltipFormat: 'DD-MM-YYYY'
},
gridLines: {
scaleShowVerticalLines: false,
display: false,
},
ticks: {
beginAtZero: false,
}
}]
},
}
});
this works as the dates now appear at dd-mm-yyy. however, the chart now begins in 1970 instead of when the data in the sql table actually begins.
any idea of how to resolve this?
This issue is best handled in the frontend rather than in the backend.
You should deine your xAxis as a time cartesian axis as follows.
options: {
...
scales: {
xAxes: [{
type: 'time',
time: {
parser: '', // define date format that matches the php data
unit: 'day',
displayFormats: {
day: 'D-M-YYYY'
},
tooltipFormat: 'D-M-YYYY'
}
...
}]
}
...
}
See Moment.js to find out about format strings that may be used for time.parser, time.displayFormats and time.tooltipFormat.
Note that Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.
UPDATE:
i've managed to have it display correctly! this is the updated chart: I did not need the parser, it understood without what needed to be passed through.
var ctx = document.getElementById("recentChart").getContext('2d');
var recentChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'hours',
data: [],
barThickness: 12,
fill: true,
backgroundColor: "rgba(54, 162, 235, 1)",
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 1,
}]
},
options: {
animation: {
duration: 1000,
easing: "linear",
},
responsive: true,
maintainAspectRatio: true,
legend: {
display: false,
position: 'bottom',
usePointStyle: true,
labels: {
fontColor: "grey",
usePointStyle: true,
},
},
scales: {
yAxes: [{
gridLines: {
display: true,
borderDash: [8, 4],
},
scaleLabel: {
display: true,
labelString: 'hours',
},
ticks: {
beginAtZero: false,
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'day',
displayFormats: {
day: 'DD-MM-YYYY'
},
},
gridLines: {
scaleShowVerticalLines: false,
display: false,
},
ticks: {
beginAtZero: true,
}
}]
},
}
});
dates now show up correctly and not from 1970.

How to show multiple datasets in line chart js

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>

How can I change the label name when you hover your data in Chart.js?

I have this line of code using a chart.js in Laravel App
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
var ctx = document.getElementById("array_crawl_source_gap").getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Google Analytics", "Google Analytics", "Web", "Web"],
datasets: [{
data: [ {{ $array_crawl_source_gap[0] }}, {{ $array_crawl_source_gap[1] }},
{{ $array_crawl_source_gap[2] }}, {{ $array_crawl_source_gap[3] }} ],
backgroundColor: [
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
]
}]
},
options: {
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
}
}],
xAxes: [{
ticks: {
beginAtZero:true,
stepSize: 100
}
}],
}
}
});
Here is the output of my code.
Expected output:
Base on my codes how can I able to make only one Google Analytics and Web in labels? And is it possible to change the labels when you hover the data as the picture below? Any idea/thoughts how can I fix this. Thank you in advance.
Custom tooltip position:
Chart.Tooltip.positioners.custom = function(elements, position) {
if (!elements.length)
return false;
var em = elements[0]._model;
return {
x: em.x-((em.x-em.base)/2),
y: em.y+em.height/4
}
}
Added tooltipText for custom tooltip titles, also callbacks to display those titles and labels. Y-axis labels have offset.
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Google Analytics", "", "Web", ""],
tooltipText: ["Wild Quess", "Very Analytical", "Fine Prediction", "Bob's opinion"],
datasets: [{
data: [ 250 , 260 , 270 , 280 ],
backgroundColor: [
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
'rgb(182, 197, 211)',
'rgba(113, 152, 214, 1.0)',
]
}]
},
options: {
responsive: false,
legend: { display: false },
tooltips: {
enabled: true,
displayColors: false,
yPadding: 10,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
titleFontColor: 'rgb(50, 100, 50)',
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
callbacks: {
title: function(tooltipItem, data) {
var title = data.tooltipText[tooltipItem[0].index];
return title;
},
label: function(tooltipItem, data) {
return tooltipItem.xLabel+' pages';
}
},
position: 'custom',
},
scales: {
yAxes: [{
ticks: {
type: 'category',
labelOffset: 35,
},
}],
xAxes: [{
ticks: {
beginAtZero:true,
stepSize: 100
}
}],
},
}
});
Manual on tooltip:
https://www.chartjs.org/docs/latest/configuration/tooltip.html
HTML in tooltip:
Chart JS Show HTML in Tooltip

Remove onhover effect from column chart

I want to remove square bracket effect on hover of column chart. I attahced screenshot. JSON code generated by PHP code.
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Jan',
'Feb',
'Mar'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tokyo',
data: [49.9, 71.5, 106.4]
}, {
name: 'New York',
data: [83.6, 78.8, 98.5]
}]
});
});
For demo http://jsfiddle.net/mvsrdzg4/
try this to remove hover effect,
xAxis: {
categories: [
'Jan',
'Feb',
'Mar'
],
crosshair: false
},

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