showing Y axis in a chart using CanvasJS - javascript

I made a chart that shows machines and the times that was taken for them to be fixed (machines X, time Y)
the data is loaded dynamically via mysql like the following
<?php
include_once(“connexion.php”);
ini_set(‘max_execution_time’,300);
//ini_set(‘error_reporting’, E_ALL);
$sq = “select machine,date_tech,time(time_fin – time_deb) as diff from action_archiv_tech WHERE (date_tech BETWEEN ‘2018-09-10’ AND ‘2018-10-06’)”;
$r = mysql_query($sq) or (die(mysql_error()));
while($tab = mysql_fetch_assoc($r)) {
$machine = $tab[‘machine’];
$diff = $tab[‘diff’];
// $data[] = [“label”=>$machine, “y”=>$diff];
$data[] = array(
‘label’ => $tab[‘machine’],
‘y’ => $tab[‘diff’]
);
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset=”UTF-8”>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart(“chartContainer”, {
theme:”light2″,
animationEnabled: true,
title:{
text: “PM”
},
axisY :{
includeZero: false,
title: “Heures”,
suffix: “H”
},
toolTip: {
shared: “true”
},
legend:{
cursor:”pointer”,
itemclick : toggleDataSeries
},
data: [
{
type: “spline”,
showInLegend: true,
yValueFormatString: “##.00H”,
name: “Curative”,
dataPoints: <?php echo json_encode($data); ?>
}
]
});
chart.render();
function toggleDataSeries(e) {
if (typeof(e.dataSeries.visible) === “undefined” || e.dataSeries.visible ){
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
</script>
</head>
<body>
<div id=”chartContainer” style=”height: 370px; max-width: 1920px; margin: 0px auto;”></div>
<script src=”../../canvasjs.min.js”></script>
</body>
</html>
However the results are not like the expected
results : https://i.stack.imgur.com/zyIZM.png
Could you please help me figure out how to solve this problem :)

It seems like you are passing date-time in y-values, whereas CanvasJS supports only numeric in axisY. Please refer documentation for more info. However you can workaround this by passing -values as timestamp and format the value in axis-labels and toolTip as shown in below example, here is the JSFiddle for the same.
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Machine Operating Time"
},
axisY: {
minimum: (new Date(2016, 0, 25, 17, 30)).getTime(),
interval: (12 * 60 * 60 * 1000),
labelFormatter: function(e){
return CanvasJS.formatDate(e.value, "DD-MMM h:mm TT");
}
},
toolTip:{
contentFormatter: function ( e ) {
return "<strong>Machine " + e.entries[0].dataPoint.label + "</strong></br> Start Time: " + CanvasJS.formatDate(e.entries[0].dataPoint.y[0], "DD-MMM h:mm TT") + "</br> Stop Time: " + CanvasJS.formatDate(e.entries[0].dataPoint.y[1], "DD-MMM h:mm TT");
}},
data: [{
type: "rangeColumn",
dataPoints: [
{ label: "A", y: [(new Date(2016, 0, 25, 18, 30)).getTime(), (new Date(2016, 0, 26, 11, 00)).getTime()] }, //.getTime() returns timestamp => y-value is numeric
{ label: "B", y: [(new Date(2016, 0, 26, 12, 00)).getTime(), (new Date(2016, 0, 27, 14, 00)).getTime()] },
{ label: "C", y: [(new Date(2016, 0, 27, 3, 30)).getTime(), (new Date(2016, 0, 27, 14, 00)).getTime()] },
{ label: "D", y: [(new Date(2016, 0, 27, 12, 00)).getTime(), (new Date(2016, 0, 28, 14, 00)).getTime()] }
]
}]
});
chart.render();
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 260px; width: 100%;"></div>

Related

Get time/date range of selected timespan apex area chart

I have some issues with apex charts. I want to create an area chart with a selectable time range on the x-axis (standard by selecting an interval by mousedraw). The "standard" example is doing what I want. But now I want to calculate with the parameters which are selected by mousedraw and write the results in a div tag.
My question is how to get the selected time range (to visualize) and the appropriate values?
The following code is the standard example from apex charts for area charts.
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart">
<div class="toolbar">
<button id="one_month">
Heute
</button>
<button id="Letzter Tag">
Gestern
</button>
<button id="one_year" class="active">
letzte Woche
</button>
<button id="ytd">
Dieser Monat
</button>
<button id="all">
letztes Halbjahr
</button>
</div>
<div id="chart-timeline"></div>
</div>
<script>
var options = {
series: [{
name: 'Energiekonsum',
data: [
[1671578047000,0.073 ],
[1671578947000,0.037 ],
[1671579847000,0.049 ],
]
},
chart: {
id: 'area-datetime',
type: 'area',
height: 350,
zoom: {
autoScaleYaxis: false
}
},
annotations: {
yaxis: [{
y: 30,
borderColor: '#999',
label: {
show: true,
text: 'Durchschnittsverbrauch',
style: {
color: "#fff",
background: '#00E396'
}
}
}],
xaxis: [{
x: new Date('14 Nov 2012').getTime(),
borderColor: '#999',
yAxisIndex: 0,
label: {
show: true,
text: 'Rally',
style: {
color: "#fff",
background: '#775DD0'
}
}
}]
},
dataLabels: {
enabled: false
},
markers: {
size: 0,
style: 'hollow',
},
xaxis: {
type: 'datetime',
min: new Date('01 Mar 2012').getTime(),
tickAmount: 6,
},
tooltip: {
x: {
format: 'dd MMM yyyy'
}
},
fill: {
type: 'gradient',
gradient: {
shadeIntensity: 1,
opacityFrom: 0.7,
opacityTo: 0.9,
stops: [0, 100]
}
},
};
var chart = new ApexCharts(document.querySelector("#chart-timeline"), options);
chart.render();
var resetCssClasses = function(activeEl) {
var els = document.querySelectorAll('button')
Array.prototype.forEach.call(els, function(el) {
el.classList.remove('active')
})
activeEl.target.classList.add('active')
}
document
.querySelector('#one_month')
.addEventListener('click', function(e) {
resetCssClasses(e)
chart.zoomX(
new Date('28 Jan 2013').getTime(),
new Date('27 Feb 2013').getTime()
)
})
document
.querySelector('#six_months')
.addEventListener('click', function(e) {
resetCssClasses(e)
chart.zoomX(
new Date('27 Sep 2012').getTime(),
new Date('27 Feb 2013').getTime()
)
})
document
.querySelector('#one_year')
.addEventListener('click', function(e) {
resetCssClasses(e)
chart.zoomX(
new Date('27 Feb 2012').getTime(),
new Date('27 Feb 2013').getTime()
)
})
document.querySelector('#ytd').addEventListener('click', function(e) {
resetCssClasses(e)
chart.zoomX(
new Date('01 Jan 2013').getTime(),
new Date('27 Feb 2013').getTime()
)
})
document.querySelector('#all').addEventListener('click', function(e) {
resetCssClasses(e)
chart.zoomX(
new Date('23 Jan 2012').getTime(),
new Date('27 Feb 2013').getTime()
)
})
</script>
If I understand you well, I think you need to enable selection on your chart and use its event function to get time range (xaxis) and values (yaxis). Inside this function, you can also write the data to a div.
Take a look at this example and play with selections (see icon at the top right corner of the chart):
const selection = document.querySelector('#selection');
let options = {
series: [{
name: 'Series',
data: [
[new Date('2022-12-28'), 100],
[new Date('2022-12-29'), 200],
[new Date('2022-12-30'), 150]
]
}],
chart: {
type: 'area',
height: 350,
toolbar: {
show: true,
tools: {
selection: true,
zoom: false,
zoomin: false,
zoomout: false,
pan: false,
reset: false,
download: false
}
},
zoom: {
enabled: false
},
selection: {
enabled: true,
type: 'xy'
},
events: {
selection: (chartContext, { xaxis, yaxis }) => {
yaxis = Array.isArray(yaxis) ? { min: yaxis[0].min, max: yaxis[0].max } : yaxis;
selection.innerHTML = `<strong>xaxis →</strong> min: <span class="min">${new Date(xaxis.min).toISOString()}</span> | max: <span class="max">${new Date(xaxis.max).toISOString()}</span><br><strong>yaxis →</strong> min: <span class="min">${yaxis.min}</span> | max: <span class="max">${yaxis.max}</span>`
}
}
},
xaxis: {
type: 'datetime',
},
tooltip: {
enabled: false
}
};
let chart = new ApexCharts(document.querySelector('#chart'), options);
chart.render();
.min {
color: green;
}
.max {
color: red;
}
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart"></div>
<div id="selection"></div>
To avoid getting undefined for yaxis.min and yaxis.max on mouse up in this particular example, I added this line of code:
yaxis = Array.isArray(yaxis) ? { min: yaxis[0].min, max: yaxis[0].max } : yaxis;
This is a bit odd, but when you release the mouse button while selecting something, yaxis is not an object literal as usual but it is an array. Could it be a bug?

Pass multiple arrays to HTML iFrame using Chart.js

I have looked at various documentation and similar questions on here, but cannot seem to find the particular solution. Apologies if I have missed anything obvious or have repeated this question!
As a bit of background info, I have implemented a graph using the Chart.js plugin and I am trying to pass the required data from a database.
The arrays of data are the following:
loggedIn: [6.3, 2.4, 7.6, 5.4, 9.9, 7.8],
available: [6.7, 2.2, 11.2, 5.5, 10.1, 7.9],
availableForExisting: [7.2, 3.1, 8.2, 5.6, 9.2, 10.2],
My problem is that only one of the line graphs is being update whilst the rest aren't. The full Chart.JS iFrame code is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="250" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
const loggedIn = [26, 36, 42, 38, 40, 30, 12];
const available = [34, 44, 33, 24, 25, 28, 25];
const availableForExisting = [16, 13, 25, 33, 40, 33, 45];
const years = [1, 2, 3, 4, 5];
var myChart = new Chart(ctx,
{
type: 'line',
data:
{
labels: years,
datasets: [
{
label: 'Start Balance',
data: loggedIn,//[], //start empty
borderColor:
[
'rgba(164,126,44,1.000)'
],
borderWidth: 1
},
{
label: 'Interest',
data: available,//[], //start empty
borderColor:
[
'rgba(5,99,59,1.000)'
],
borderWidth: 1
},
{
label: 'End Balance',
data: availableForExisting,//[], //start empty
borderColor:
[
'rgba(255,148,112,1.000)'
],
borderWidth: 1
}
]
},
options:
{
tooltips:
{
callbacks:
{
label: function(tooltipItem, data)
{
const title = data.labels[tooltipItem.index];
const dataset = data.datasets[tooltipItem.datasetIndex];
const value = dataset.data[tooltipItem.index];
return title + ': ' + Number(value).toFixed(2) + "%";
}
},
},
onClick: handleClick
}
});
window.onmessage = function(event)
{
if (event.data && Array.isArray(event.data))
{
myChart.data.datasets[0].data = event.data[0];
myChart.data.datasets[1].data = event.data[1];
myChart.data.datasets[2].data = event.data[2];
myChart.update();
}
else
{
console.log("HTML Code Element received a generic message:");
console.log(event.data);
}
};
function handleClick(e)
{
var activeBars = myChart.getElementAtEvent(e);
var value = myChart.config.data.datasets[activeBars[0]._datasetIndex].data[activeBars[0]._index];
var label = activeBars[0]._model.label;
window.parent.postMessage(
{
"type": "click",
"label": label,
"value": value
}, "*");
}
function ready()
{
window.parent.postMessage(
{
"type": "ready"
}, "*");
}
</script>
</body>
</html>
I need to display the data in multiple line graphs, however only one is being updated. The way I am passing the data from the frontend is as follows:
let data =
{
loggedIn: [6.3, 2.4, 7.6, 5.4, 9.9, 7.8],
available: [6.7, 2.2, 11.2, 5.5, 10.1, 7.9],
availableForExisting: [7.2, 3.1, 8.2, 5.6, 9.2, 10.2],
};
$w("#html4").postMessage(data);
$w("#html4").onMessage((event) =>
{
if (event.data.type === 'ready')
{
$w("#html4").postMessage(days[year]);
}
});

Show quarter markers instead of years in JSCharting Gantt Chart

I am new to this JSCharting library and working with it to create a Gantt Chart. When I map my data on the chart, it slices the Y Axis based on years. I am trying to slice it based on 3 months intervals. Instead of 2021, 2022, 2023, I want to show Q1, Q2, Q3, Q4 for each year.
One quick and dirty solution I found is below, to create markers on Y Axis like this:
{
yAxis: {
markers: [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028].reduce(
(all: { label: { text: string; color: string }; value: string }[], year) => {
return [
...all,
...[1, 4, 7, 10].map((month) => ({
label: {
text: month === 1 ? "Q1" : month === 4 ? "Q2" : month === 7 ? "Q3" : "Q4",
color: "#ddd",
},
color: "#ddd",
value: `${month}/1/${year}`,
legendEntry: {
visible: false,
},
})),
];
},
[]
),
},
}
However, when I do that, first line of data covers the quarter labels like so.
Is there a proper way to do this and show it in the bottom with along with years? I'd appreciate any help.
You can use calendar patterns to create ticks for quarters and months more easily. Here's an example.
var chart = JSC.chart('chartDiv', {
debug: true,
axisToZoom: 'x',
margin_right: 10,
xAxis: {
scale_type: 'time',
defaultTick_enabled: false,
customTicks: [
{
value_pattern: 'month',
label_text: '%min'
},
{
value_pattern: 'quarter',
label_text: qTickText
},
{
value_pattern: 'year',
label_text: '%min'
}
]
},
legend_visible: false,
title_label_text:
'Apple iPhone sales (in million units)',
series: [
{
type: 'line spline',
defaultPoint: {
marker: {
outline: { width: 2, color: 'white' }
}
},
points: [
{ x: '04/1/2016', y: 74.78 },
{ x: '07/1/2016', y: 51.19 },
{ x: '10/1/2016', y: 40.4 },
{ x: '1/1/2017', y: 45.51 },
{ x: '04/1/2017', y: 78.29 },
{ x: '07/1/2017', y: 50.76 },
{ x: '10/1/2017', y: 41.03 },
{ x: '1/1/2018', y: 46.68 },
{ x: '04/1/2018', y: 67.32 },
{ x: '07/1/2018', y: 52.22 },
{ x: '10/1/2018', y: 41.3 },
{ x: '1/1/2019', y: 46.89 }
]
}
]
});
function qTickText(v) {
return dateToQuarter(v[0]);
}
function dateToQuarter(d) {
d = new Date(d);
return 'Q' + (Math.floor(d.getMonth() / 3) + 1);
}

What is the proper way of visualizing data?

I am trying to plot chart using canvas.js!
As I want the data dynamically from my API, I created an array and is then passing it into the json object.
so I did the following:
<!DOCTYPE HTML>
<html>
<head>
<script>
var xhr = new XMLHttpRequest(),
method = "GET",
url = "url";
xhr.open(method, url, true);
var data_array = [];
xhr.send();
window.onload = function () {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var api_data = xhr.responseText;
var api_json = JSON.parse(api_data);
var data = api_json["data"];
for(var i=0; i<data.length; i++) {
dp_data = data[i];
dp_median = dp_data["dp_median_price"];
dp_date = dp_data["date"];
var datearray = dp_date.split("-");
var newdate = datearray[0] + ', ' + datearray[1] + ', ' + datearray[2];
data_array.push({x:newdate, y:Number(dp_median)});
}
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "title"
},
axisX: {
valueFormatString: "YYYY MM DD"
},
axisY2: {
title: "Median Price",
prefix: "₹",
suffix: ""
},
toolTip: {
shared: true
},
legend: {
cursor: "pointer",
verticalAlign: "top",
horizontalAlign: "center",
dockInsidePlotArea: true,
itemclick: toogleDataSeries
},
data:[
{
type:"line",
axisYType: "secondary",
name: "name1",
showInLegend: true,
markerSize: 1,
yValueFormatString: "₹#,###",
dataPoints: [
{ x: new Date(2015, 08, 01), y: 648 },
{ x: new Date(2015, 09, 01), y: 649 },
{ x: new Date(2015, 10, 01), y: 649 },
{ x: new Date(2017, 03, 01), y: 400 },
{ x: new Date(2017, 04, 01), y: 749 },
{ x: new Date(2017, 05, 01), y: 740 }]
},
{
type:"line",
axisYType: "secondary",
name: "name2",
showInLegend: true,
markerSize: 1,
yValueFormatString: "₹#,###",
dataPoints: data_array
}
]
});
chart.render();
function toogleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else{
e.dataSeries.visible = true;
}
chart.render();
}
}
}
};
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
Here, I cant read the data_array. How do I pass it in the chart data?
Above way is not working!
But when I pass data in a static way it works!
My array is in exact format as shown example of static information!
output of console.log(data_array) =
0:
x: "2019, 08, 29"
y: 1935
__proto__: Object
The problem is in how you try to track your ajax request.
The onredystatechange event fires multiple times during the executon of the xhr request.
0 - UNSENT Client has been created. open() not called yet.
1 - OPENED open() has been called.
2 - HEADERS_RECEIVED send() has been called, and headers and status are available.
3 - LOADING Downloading responseText holds partial data.
4 - DONE The operation is complete.
It is only when the state is 4 that you should start processing your data.
xhr.onreadystatechange = function () {
if (xhr.readyState ==0 4 and xhr.status === 200) {
//Process your data

How to reload data in Google Charts Calendar while keeping selected cell?

I use jQuery and I use the following JS function to load and reload / redraw the Google Chart Calendar.
It works, however, it also removes the border from the selected item. I want to reload the calendar data, while keeping the currently selected item selected.
Any ideas?
function refreshCalendar( rows)
{
//if( calendar != 0 )
{
calendar = new google.visualization.Calendar(document.getElementById('calendar_basic'))
google.visualization.events.addListener(calendar, 'select', calendarSelectHandler);
calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows( rows );
calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
}
}
Normally, you would use chart.getSelection and chart.setSelection.
Get selection on 'select' event
Set selection on 'ready' event
getSelection works fine, but setSelection doesn't work with the Calendar chart.
No error is thrown, but nothing is selected.
I tried versions '41' thru 'current'...
To demonstrate, the following example uses both a Calendar chart and a Column chart.
Make a selection on both charts, then click "Redraw Chart".
The selection for the Column chart remains but not on the Calendar.
google.charts.load('current', {
callback: drawChart,
packages: ['calendar', 'corechart']
});
function drawChart() {
var selectionCal;
var selectionCol;
var calendar = new google.visualization.Calendar(document.getElementById('calendar'))
google.visualization.events.addListener(calendar, 'select', function () {
selectionCal = calendar.getSelection();
});
google.visualization.events.addListener(calendar, 'ready', function () {
if (selectionCal) {
calendar.setSelection(selectionCal);
}
});
var column = new google.visualization.ColumnChart(document.getElementById('column'))
google.visualization.events.addListener(column, 'select', function () {
selectionCol = column.getSelection();
});
google.visualization.events.addListener(column, 'ready', function () {
if (selectionCol) {
column.setSelection(selectionCol);
}
});
document.getElementById('test_button').addEventListener('click', function () {
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}, false);
var calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows([
[ new Date(2012, 3, 13), 37032 ],
[ new Date(2012, 3, 14), 38024 ],
[ new Date(2012, 3, 15), 38024 ],
[ new Date(2012, 3, 16), 38108 ],
[ new Date(2012, 3, 17), 38229 ],
]);
var calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="calendar"></div>
<div id="column"></div>
<input type="button" id="test_button" value="Redraw Chart" />
I can also confirm that the setSelection() method doesn't change anything on the UI for the calendar chart.
So I looked up what happens after selecting a day in the chart with the mouse. Then I implemented a simple DOM manipulation logic which does the same. You can use that logic as a replacement of the setSelection() use case. (It is just a quick prototype, but I hope it helps you, too).
For a litte demo I adjusted #WhiteHat snippet / the selected day survives now the refresh action (doesn't work with charts which needs to display more than one year!):
google.charts.load('current', {
callback: drawChart,
packages: ['calendar', 'corechart']
});
function drawChart() {
var selectionCal;
var selectionDate;
var selectionCol;
var calendar = new google.visualization.Calendar(document.getElementById('calendar'))
google.visualization.events.addListener(calendar, 'select', function () {
selectionCal = calendar.getSelection();
selectionDate = new Date(selectionCal[0].date);
});
google.visualization.events.addListener(calendar, 'ready', function () {
if (selectionDate) {
// google calendar setSelection BUG :/
// https://stackoverflow.com/a/36093217/810944
// do it manually
var doy = selectionDate.getDOY();
markDayInChart(doy);
}
});
var column = new google.visualization.ColumnChart(document.getElementById('column'))
google.visualization.events.addListener(column, 'select', function () {
selectionCol = column.getSelection();
});
google.visualization.events.addListener(column, 'ready', function () {
if (selectionCol) {
column.setSelection(selectionCol);
}
});
document.getElementById('test_button').addEventListener('click', function () {
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}, false);
var calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows([
[ new Date(2012, 3, 13), 37032 ],
[ new Date(2012, 3, 14), 38024 ],
[ new Date(2012, 3, 15), 38024 ],
[ new Date(2012, 3, 16), 38108 ],
[ new Date(2012, 3, 17), 38229 ],
]);
var calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}
function markDayInChart(dayOfYear) {
// clones the logic for clicking / selecting a day via mouse
// keep in mind to clean up the adjusted and added `rect`-elements if you do not use full page reloads!
// doesn't work with charts which needs to display more than one year!
var days_all_svg_group = $('#calendar svg').children('g')[1];
var days_marked_svg_group = $('#calendar svg').children('g')[4];
var day_svg_rect = $('rect:nth-of-type('+dayOfYear+')',$(days_all_svg_group));
// hide the original rect
$(day_svg_rect).css('display: none;');
// add a cloned rect with a different stroke
var day_marked_svg_rect = $(day_svg_rect).clone();
$(day_marked_svg_rect).attr({stroke: '#000000', 'stroke-width': 2});
$(day_marked_svg_rect).attr('stroke-opacity', null);
$(days_marked_svg_group).append(day_marked_svg_rect);
}
// https://stackoverflow.com/a/26426761/810944
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
if((year & 3) != 0) return false;
return ((year % 100) != 0 || (year % 400) == 0);
};
// Get Day of Year
Date.prototype.getDOY = function() {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var mn = this.getMonth();
var dn = this.getDate();
var dayOfYear = dayCount[mn] + dn;
if(mn > 1 && this.isLeapYear()) dayOfYear++;
return dayOfYear;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="calendar"></div>
<div id="column"></div>
<input type="button" id="test_button" value="Redraw Chart" />

Categories

Resources