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.
Related
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>
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
I am using Highcharts to display transaction status for different months. The chart is displaying fine. To show the number of transactions for each month, I have placed a datalabel on top of each column. The code is given below:
$(function () {
$('#hc').highcharts({
chart: {
renderTo: 'container',
type: <?php echo $type ; ?>,
marginRight: 130,
marginBottom: 35
},
title: {
text: 'Transaction Status',
x: -20
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: <?php echo $monnth_series ?>
},
yAxis: {
title: {
text: 'Transactions'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
color: '#fff',
style: {fontWeight: 'bold'},
formatter: function() {return this.y},
y: -5,
rotation: 360
},
column: {
pointPadding: .2,
groupPadding: 0,
borderWidth: 1
}
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +': '+ this.y; +'</b>'
}
},
credits: { enabled: false },
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -6,
y: 90,
borderWidth: 0
},
series: <?php echo $series_data ?>
});
});
Now I want to place another datalabel on the body of the column which will show the type of the transaction.
If I try
formatter: function() {return this.series.name},
inside: true,
then the datalabel shows correctly but the datalabel on top of the column does not show up.
Any idea on how to do this ?
Question: PDF generated by Phantomjs has additional grey bars coming in the Graph.
Set up: My Front end is using highcharts to create graphs for the pages.
I have used phantomjs to create PDF from the HTML page.
Sample: attached image
My Attempts: Followed numerous posts and answers to the same topic and gave the following tries but unsuccessful.
Disable animation and enableMouseTracking for whole chart.
$('#graph').highcharts({
chart: {
type: 'bar',
animation: false,
enableMouseTracking: false
},
Disable animation and enableMouseTracking in PlotOptions:
plotOptions: {
bar: {
animation: false,
enableMouseTracking: false
},
series: {
stacking: 'normal',
animation: false,
enableMouseTracking: false,
shadow:false
Disabling tool tip:
tooltip: {
enabled: false
},
$('#graph').highcharts({
chart: {
type: 'bar',
animation: false,
enableMouseTracking: false
},
title: {
text: 'Online Survey Results'
},
xAxis: {
categories: data
},
yAxis: {
min: 0,
max: maxTotalAnswerWeight,
tickInterval: Math.round(tickInterval),
minorGridLineWidth: 0,
minorTickInterval: Math.round(tickInterval),
minorTickLength: 10,
minorTickWidth: 1,
lineWidth: 1,
title: {
text: 'Progress'
},
labels: {
enabled: true,
align: 'right',
rotation: -45,
formatter: function() {
//console.log(this.value)
var tickMarkNumber = this.value/Math.round(tickInterval);
return seriesData[tickMarkNumber]
},
style: {
fontSize: '14px',
fontFamily: 'proxima-nova,helvetica,arial,sans-seri',
/*whiteSpace: 'nowrap',
paddingLeft: 50,
paddingRight: '100px',
marginLeft: "50px",
padding: 10,
paddingBottom: '10px'*/
}
}
},
legend: {
reversed: true
},
tooltip: {
enabled: false
},
plotOptions: {
bar: {
animation: false,
enableMouseTracking: false
},
series: {
stacking: 'normal',
animation: false,
enableMouseTracking: false,
shadow:false
/*dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
}*/
}
},
colors: ['green','gray'],
series: [{
index: 1,
name: 'Progress made',
data: achievedData
}, {
index: 0,
name: 'Progress yet to be made',
data: yetToAchievedData
}]
});
},
Is there anything very fundamental I am missing here?
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.