ChartJS - Highlight Weekends and Lowest and Highest Values - javascript

I'm using ChartJS and I'd like to highlight all Saturdays and Sundays as a different colour - I'd also light to highlight the highest and lowest values in the chart.
Is this possible?
Fiddle so far:
http://jsfiddle.net/3wku56Lq/
new Chart(document.getElementById("myChart"), {
type: 'bar',
data: {
labels: ['14 May 2019 (Tue)', '15 May 2019 (Wed)', '16 May 2019 (Thu)', '17 May 2019 (Fri)', '18 May 2019 (Sat)', '19 May 2019 (Sun)', '20 May 2019 (Mon)', '21 May 2019 (Tue)', '22 May 2019 (Wed)', '23 May 2019 (Thu)', '24 May 2019 (Fri)', '25 May 2019 (Sat)', '26 May 2019 (Sun)', '27 May 2019 (Mon)', '28 May 2019 (Tue)', '29 May 2019 (Wed)', '30 May 2019 (Thu)', '31 May 2019 (Fri)', '01 Jun 2019 (Sat)', '02 Jun 2019 (Sun)', '03 Jun 2019 (Mon)', '04 Jun 2019 (Tue)', '05 Jun 2019 (Wed)', '06 Jun 2019 (Thu)', '07 Jun 2019 (Fri)'],
datasets: [{
data: [25738, 25261, 25499, 24178, 12400, 13356, 26033, 26588, 25018, 22972, 21702, 11232, 11617, 14308, 24212, 23949, 23708, 21511, 11545, 13836, 25536, 26824, 0, 0, 0],
label: "Impressions",
backgroundColor: 'rgb(199, 199, 199, 0.7)',
borderColor: 'rgb(199, 199, 199)',
fill: true
}
]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var value = data.datasets[0].data[tooltipItem.index];
value = value.toString();
value = value.split(/(?=(?:...)*$)/);
value = value.join(',');
return value;
}
} // end callbacks:
}, //end tooltips
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
userCallback: function(value, index, values) {
// Convert the number to a string and splite the string every 3 charaters from the end
value = value.toString();
value = value.split(/(?=(?:...)*$)/);
value = value.join(',');
return value;
}
}
}],
xAxes: [{
ticks: {
}
}]
}
}
});

You can highlight weekends using map functions:
http://jsfiddle.net/75apft3m/
Also, you can do the same with the lowest and highest value.
But for this you must store that arrays somewhere.
Like this:
http://jsfiddle.net/75apft3m/1/
Just use Math.max.apply(null, dataArray)
and Math.min.apply(null, dataArray) to find highest and lowest values :)

Related

Date formatting for X-axis labels only showing as 'Jan'

I am trying to create a line chart where the x-axis is in the format of "Month Year" (ex Jun 2014), but instead of showing the month of the actual data point the ticks are all showing as **Jan** and the labels don't match up with the plot points.
I am expecting there to be 3 XLabels for Jun 2014, Jun 2015, Jun 2016 but instead, there are only 2 labels for Jan in between.
var data1 = [{
x: '06/01/2014',
y: 1853
}, {
x: '06/01/2015',
y: 5087
}, {
x: '06/01/2016',
y: 3078
}];
data1.forEach(function(el, i) {
data1[i].x = new Date(el.x).getTime();
});
Highcharts.chart('container', {
chart: {
type: 'area'
},
xAxis: {
type: 'datetime',
labels: {
formatter: function(){
return Highcharts.dateFormat("%b %Y", this.value)
}
}
},
series: [{
name: 'Data',
data: data1
}]
});
Fiddle
You can take advantage of tickPositioner:
xAxis: {
tickPositioner: function() {
return this.series[0].xData;
},
...
}
Live demo: http://jsfiddle.net/BlackLabel/of7k0vxh/
API Reference: https://api.highcharts.com/highcharts/xAxis.tickPositioner

Chart.js xAxes Date Labels are altered based on screen width

I've been messing around with chart.js time options (displayFormat and tooltipFormat):
type: 'time',
unit: 'day',
unitStepSize: 1,
time: {
displayFormats: {
'day': 'dd',
},
tooltipFormat: 'll'
},
Which works as expected - on a 17inch laptop screen.
This shows dates as Mo, Tu, We, Th, Fr, Sa, Su.
However on a 24inch monitor chart.js automatically alters the dates and they become:
Aug 18 12AM - Aug 18 12PM, Aug 19 12AM - Aug 19 12PM, etc
How can I stop this from happening?
You need to set the hour property of displayFormats to dd as well, like so :
...
time: {
displayFormats: {
'day': 'dd',
'hour': 'dd' //<-- set this
},
tooltipFormat: 'll'
},
...

Why Chart.js v2 time based data not aligning with X axis correctly?

When displaying time based data using Chart.js, the data itself doesn't seem to be aligned with the X axis labels. For instance, when the data is for 2016-11-30, the bar is actually showing in December. The last date in a series of dates doesn't even show on the chart. How can I make them align correctly?
$(document).ready(function(){
var config = {
type: 'bar',
data: {
labels: [
'2016-11-30', // Why showing in December?
'2017-04-01', // Why not showing in beginning of April?
'2017-06-30'], // Why not showing?
datasets: [{
label: 'Contacts',
backgroundColor: 'red',
data: [
1,
5,
7
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
stepSize:1
}
}],
xAxes: [{
type: 'time',
barThickness:2,
time: {
unit: 'month'
}
}]
}
}
};
var Canvas = $("#Chart");
var cc = new Chart(Canvas, config);
});
Example on Codepen:
https://codepen.io/skunkbad/pen/EmBJMa
Regarding the showing on the wrong date:
This is because of how you instantiate a date object and how it relates to timezones, your browser is likely resolving that to your timezone and you get a different value.
I am on GMT-3 and this is what happens for me for example:
$ new Date('2016-11-30')
- Tue Nov 29 2016 21:00:00 GMT-0300 (BRT)
$ new Date(2016, 11, 30)
- Fri Dec 30 2016 00:00:00 GMT-0300 (BRT)
Regarding not showing last data:
The bar is plotted but it's not on visible location. It's possible to verify this on this JSFiddle (not sure why not on codepen), if you move your mouse to the very edge of the screen the label will appear.
This is a known issue and is being tracked here: #2415
If possible, I think that the easiest workaround would be to manually define a max property on your time scale

Highcharts use dateTime for chart generation

I am using high-charts library to draw charts on my project.
and i am facing an issue while displaying labels on X axis.
Graph is being drawn efficiently as per the values but X axis labels are not good and not as i want.
The Data is as below:
seriesData
Wed May 25 2016 17:19:52 GMT+0530 (India Standard Time),983.49,
Thu May 26 2016 17:19:52 GMT+0530 (India Standard Time),1000.3,
Fri May 27 2016 17:19:52 GMT+0530 (India Standard Time),996.24,
Sat May 28 2016 17:19:52 GMT+0530 (India Standard Time),996.75,
Sun May 29 2016 17:19:52 GMT+0530 (India Standard Time),996.75,
Mon May 30 2016 17:19:52 GMT+0530 (India Standard Time),1001.75,
Tue May 31 2016 17:19:52 GMT+0530 (India Standard Time),999.86,
Wed Jun 01 2016 17:19:52 GMT+0530 (India Standard Time),1003.16,
Thu Jun 02 2016 17:19:52 GMT+0530 (India Standard Time),996.35,
Fri Jun 03 2016 17:19:52 GMT+0530 (India Standard Time),990.99
And Highcharts JS is as below
Highcharts.setOptions({
global:
{
useUTC: currentTime.getUTCHours()==currentTime.getHours()
}
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'linechartjs',
zoomType: 'x'
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%e.%m',
year: '%e.%m.%Y'
},
},
yAxis: {
title: {
text: ''
},
min: minY,
max: maxY,
tickInterval: increment,
opposite: true
},
plotOptions: {
line: {
dataLabels: {
enabled: false
},
marker: {
enabled: false
},
enableMouseTracking: false
}
},
exporting: {
buttons: {
contextButton: {
enabled: false
}
}
},
credits: {
enabled: false
},
series: [{
showInLegend: false,
name: '',
color: '#333',
data: seriesData,
}]
});
})
The X axis labels are as below:
X axis labels shall be in Date Format like 25.05, 26.05 .. and so on
Readers: This answer has been updated based on further input from the
questioner. Please see below.
It looks like you don't need all of that code for your dateTimeLabelFormat attribute.
From your example, it seems what you want is two-digit day and two-digit month. In that case, all you need for your x-axis labels is:
dateTimeLabelFormats: {
day: '%d.%m'
}
Here's an example fiddle (from a Highcharts demo) with this label format: http://jsfiddle.net/brightmatrix/zxt39L7g/
And here's the resulting chart:
Please let me know if this is helpful for you.
I did some further research based on the comments Gags provided
and came up with additional label formatting and intervals. These
settings can be changed based on what the user chooses in a dropdown
menu (see the comments).
First, I created the dropdown menu:
<select id="chooseDateRange">
<option value="">- choose a date range -</option>
<option value="1day">one day</option>
<option value="1week">one week</option>
<option value="1month">one month</option>
<option value="1year">one year</option>
<option value="5years">five years</option>
</select>
Second, I created a Javascript function to set and define values based on what the user chose in this menu:
// initialize local variables for the chart's options
var selectedPointInterval = 0;
var selectedPointIntervalUnit = 'day';
// set values based on which date range the user chose
function setDateRangeAndLabels(value) {
switch(value) {
case "1day":
selectedPointIntervalUnit = 'day';
selectedPointInterval = 1;
break;
case "1week":
selectedPointIntervalUnit = 'day';
selectedPointInterval = 7;
break;
case "1month":
selectedPointIntervalUnit = 'month';
selectedPointInterval = 1;
break;
case "1year":
selectedPointIntervalUnit = 'year';
selectedPointInterval = 1;
break;
case "5years":
selectedPointIntervalUnit = 'year';
selectedPointInterval = 5;
break;
default:
selectedPointIntervalUnit = 'day';
selectedPointInterval = 1;
break;
}
chartOptions.plotOptions.series.pointInterval = selectedPointInterval;
chartOptions.plotOptions.series.pointIntervalUnit = selectedPointIntervalUnit;
};
Third, I set the chart's options to a variable called chartOptions'. I moved the attributes that setpointStarttoplotOptions.series` to make them universal for all series.
// define the chart's options
var chartOptions = {
plotOptions: {
series: { pointStart: Date.UTC(2010, 0, 1) }
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%d.%m',
week: '%d.%m',
month: '%m.%y',
year: '%m.%y'
}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
};
Finally, I created code to draw the chart upon first loading the page, as well as a jQuery function to redraw it based on the user choosing a new range from the dropdown menu:
// draw the chart
setDateRangeAndLabels('1day');
var chart = $('#container').highcharts(chartOptions);
// redraw the chart based on new date range
$('#chooseDateRange').change(function (){
setDateRangeAndLabels(this.value);
chart = $('#container').highcharts(chartOptions);
});
Here's the complete fiddle for review: http://jsfiddle.net/brightmatrix/zxt39L7g/
Please note: This will only change the x-axis labels, intervals, and
default tooltip text for the data that the chart is given. To get data
that's relevant to the date intervals chosen, you'll need to also
dynamically change the series data based on the user's choice.

"Last domain does not have enough data columns" when combining Candlestick and Line chart for Google Charts

I am trying to render both a CandleStick chart with a Line chart.
Here is the JSFiddle of my failing example: https://jsfiddle.net/7wyp6yy3/1/
Here is the JSFiddle of my CandleStick chart: https://jsfiddle.net/7jadqnsb/
What I did, on top of my Candlestick code, I added the default seriesType of candlesticks, and assigned the 5-th column as a line-chart
seriesType: 'candlesticks',
series: {4: {type: 'line'}}
For my data, I simply added a fourth column of integers:
["Mon, Aug 10 2015",2080.98,2080.98,2104.18,2105.35, 500],
["Tue, Aug 11 2015",2076.49,2102.66,2084.07,2102.66, 500],
["Wed, Aug 12 2015",2052.09,2081.10,2086.05,2089.06, 500],
["Thu, Aug 13 2015",2078.26,2086.19,2083.39,2092.93, 500],
["Fri, Aug 14 2015",2080.61,2083.15,2091.54,2092.45, 500],
["Mon, Aug 17 2015",2079.30,2089.70,2102.44,2102.87, 500],
["Tue, Aug 18 2015",2094.14,2101.99,2096.92,2103.47, 500],
["Wed, Aug 19 2015",2070.53,2095.69,2079.61,2096.17, 500],
["Thu, Aug 20 2015",2035.73,2076.61,2035.73,2076.61, 500],
["Fri, Aug 21 2015",1970.89,2034.08,1970.89,2034.08, 500],
["Mon, Aug 24 2015",1867.01,1965.15,1893.21,1965.15, 500],
["Tue, Aug 25 2015",1867.08,1898.08,1867.61,1948.04, 500],
["Wed, Aug 26 2015",1872.75,1872.75,1940.51,1943.09, 500],
["Thu, Aug 27 2015",1942.77,1942.77,1987.66,1989.60, 500],
That said, I am getting the following error with my new code:
Last domain does not have enough data columns (missing 3)
I tried changing the series index to a variety of values, but no dice.
You must set series.1 , the number doesn't refer to a column, it's the index of a serie.
What happens: default serieType is candlesticks, so the first serie (index: 0 ) will automatically be of type "candlesticks"...a candlestick-chart requires 4 data-columns
When you set series.4 the API will automatically create series.0, series.1, series.2 and series.3 ....and all of them will be candlesticks
Let's see the data-columns as a stack of data.
The API creates the series:
serie.0
...will be candlesticks , requires 4 data-columns, the first 4 data-columns will be removed from the stack
serie.1
...also candlesticks, requires 4 data-columns, but there is only 1 data-column left on the stack (3 are missing....that's what the error means)
I know this is a bit old, but I just ran into the same problem. Dr.Molle's answer put me in the right direction, but I think it could use a bit more clarification.
In summary your last column should be put at the beginning so that it looks like:
["Mon, Aug 10 2015",500,2080.98,2080.98,2104.18,2105.35],
["Tue, Aug 11 2015",500,2076.49,2102.66,2084.07,2102.66],
["Wed, Aug 12 2015",500,2052.09,2081.10,2086.05,2089.06],
...
Then in your 'options' variable you can put:
seriesType: 'candlesticks',
series: {0: {type: 'line'}}
Hope this helps other in the future!
as a kind of an answer to theGreenCabbage's question on the accepted answer:
So right now we added one more line to the candlestick. Could I add another set/column of line chart data on top of the existing?
function drawChart(data) {
if (data == null) return;
var formattedData = [];
for (var i = 0; i < data.length; i++) {
var rowItem = [data[i].date, data[i].low, data[i].open, data[i].close, data[i].high, data[i].line1, data[i].line2, data[i].line3];
formattedData.push(rowItem);
}
var dt = google.visualization.arrayToDataTable(formattedData, true);
var options = {
legend: 'none',
candlestick: {
fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
risingColor: { strokeWidth: 0, fill: '#0f9d58' } // green
},
chartArea: { left: 40, top: 20, width: '100%', height: '75%' },
seriesType: 'candlesticks',
series: { 1: { type: 'line' },
2: { type: 'line' },
3: { type: 'line' } },
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(dt, options);
}
well, the main parts of this function in the context of the question are:
var rowItem = [data[i].date, data[i].low, data[i].open, data[i].close, data[i].high, data[i].line1, data[i].line2, data[i].line3];
and
series: { 1: { type: 'line' },
2: { type: 'line' },
3: { type: 'line' } },
all the other parts are simply for those who want to take in the CTRL+C / CTRL+V way

Categories

Resources