ChartJS date formating - javascript

I am trying to make a graph that shows how much power solarpanels are produsing using chartJS. I am using data in the following format
{x: Fri Mar 19 2021 06:20:28 GMT+0100 (centraleuropeisk normaltid), y: 1.88}
And it makes a graph but the x values is not in a readable date format. The graph liks like this:
Link to picture of graph (I am not allowed to post images yet apparently)
https://i.imgur.com/HUOHoqg.png
To make the graph I use this code:
var ctx = document.getElementById("lineChart");
var line = new Chart(ctx, {
type: "scatter",
data: {
datasets: [
{
data: power,
borderColor: "#ffd420",
showLine: true,
fill: false,
},
],
},
options: {
tooltips: { enabled: false },
hover: { mode: null },
elements: {
point: {
radius: 0,
},
},
//---
xAxes: [],
//--
},
});
I have tried to play with the xAxes settings but it still show a large number instead of a date.
Does anyone know what settings can fix this or do I need to change the format of the input?
I have searched alot but I can't find a solution to this problem.

There are 2 options, you can make use of the timescale provided by chart.js in here you can set what format you want it to show the dates: https://www.chartjs.org/docs/latest/axes/cartesian/time.html
The other options is to use the tick callback to do it yourself like this:
options: {
scales: {
xAxes: [{
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
const date = new Date(value)
return `${date.getDate()}/${date.getMonth()}/${date.getFullYear()}`
}
}
}]
}
}

Related

ChartJS x-axis show only months of year

So I'm making this mobile app using Cordova, which allows me to use HTML, CSS and JavaScript. I'm currently using SQLite as a database (works almost same as mySQL) but that isn't that important. All I do is get my data from that database. I get both the date (of when the data was added to the Database) and the weight of a person.
I'm using a linegraph which show the weight on the Y-axis and the data on the X-axis.
What I want to do is only show the months as labels on the x-axis but still make it so that it show data for each day seperate. So for example if I add data on the 1st of January, the 2nd of January and the 3rd of January. I want to be able to see all 3 days as dots on my graph but on the X-axis it should only say 'January'.
I've been looking into the 'time' option of Chart.JS but can't really make any sense of how I'm supposed to do it.
HTML:
<canvas id="myChart" style="margin-top: 20px;"></canvas>
JavaScript:
//these are the arrays that I will fill dynamically. Labels will be my months and data will be the weight
var labels = [];
var data = [];
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: labels,
datasets: [{
backgroundColor: 'rgba(255, 119, 0, 0.5)',
borderColor: 'rgba(255, 119, 0, 1)',
data: data
}]
},
// Configuration options go here
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Use the time-type in your x-axis. With time: { unit: 'month' } (always months) or minUnit (months and years if necessary) you can get the month labels.
As label for your data you need to pass a Date or moment
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month'
}
}],
}
Here is a complete example.
Check the moment docs for dates, especially the creation and parsing of dates. Chart.js works with moment dates so it's quite important (and quite easy btw).

Why the draggable plugin does not work for a radar chart in ChartJS?

Currently I am building a frontend application, that uses data like AirQuality and information about POIs. For displaying the rating of the single points I am using a radar chart with ChartJS (using it the First Time ever!).
I can already change the chart with input data, that is pushed to the chart after a button click. Another functionality I wanted to implement is the possibility to drag the endpoints of the radar chart to change the values.
I found the draggable plugin and I have tried to implement it, but it does not work like I thought it would.
This is the first time I am working with chartJS and I have found myself confused with the documentation about the plugin.
I am using plain JavaScript. No frameworks at all.
Here is the code for my chart:
var data = {
labels: ["Air", "POI", "Noise"],
datasets: [{
backgroundColor: "#50237f",
borderColor: "#50237f",
data: [33.3333333333, 33.3333333333, 33.3333333333],
label: 'Rating'
}]
};
var options = {
scale: {
ticks: {
min: 0,
max: 100,
stepSize: 25,
showLabelBackdrop: false
}
},
maintainAspectRatio: true,
spanGaps: false,
elements: {
line: {
tension: 0.000001
}
},
};
var ctx = document.getElementById("ratingChart");
var myChart = new Chart(ctx, {
type: 'radar',
data: data,
options: options,
config: {
plugins: {
// maybe set the plugin here? but how?
}
}
});

C3 Line graph displaying hh:mm:ss

Is this possible to do?
I have a lite graph that is tracking check in times for patients. This time might be coming back as 01:10:45 or 00:45:00 or something similar. And I'm trying to plot this on a graph so the receptionist can see how much time it takes for something to check into the clinic.
Initially I was just plotting this in minutes, but was just told that was not going to cut it. I couldn't find any documentation on this and I've tried everything I can think of.
This is kind of what my code looks like
waitAverage = []
for(looping through all my data here){
waitAverage.push(moment(data[i].AverageWaitTime, "hh:mm:ss").format('HH.mm.ss')); //I have also tried formatting it like HH:mm:ss. I thought maybe decimals would help
waitAverage.unshift(label)
}
arrayHolder.push(waitAverage);
c3.generate({
bindto: '.timeline',
data: {
columns: arrayHolder,
axes: {
data1: 'x'
}
},
axis: {
y: {
label: { // ADD
text: text,
position: 'outer-middle'
}
},
x: {
type: 'category',
categories: hour //This does exist I just didn't include the variable here
}
}
});
Any help would appreciated!
For anyone who needs an answer for this I was able to figure it out!
In the axis you have to call the tick format function and do some weird rounding.
axis: {
y: {
label: { // ADD
text: text,
position: 'outer-middle'
},
tick: {
format: function (d) {
return app.moment(Math.round(d*100)/100, "hh.mm").format('H:mm');
}
}
},
x: {
type: 'category',
categories: hour
}
}

Highcharts not plotting Date string as Category

I am using Highcharts to plot JSON Data. The dates are in the string format.
JSON Data:
[{"BRENT_SPOT":70.88,"TRADE_DATE":"31-JUL-2009"},{"BRENT_SPOT":73.28,"TRADE_DATE":"03-AUG-2009"},{"BRENT_SPOT":74.31,"TRADE_DATE":"04-AUG-2009"},{"BRENT_SPOT":74.96,"TRADE_DATE":"05-AUG-2009"},{"BRENT_SPOT":74.4,"TRADE_DATE":"06-AUG-2009"},{"BRENT_SPOT":72.84,"TRADE_DATE":"07-AUG-2009"},{"BRENT_SPOT":73.29,"TRADE_DATE":"10-AUG-2009"},{"BRENT_SPOT":72.04,"TRADE_DATE":"11-AUG-2009"}]
HighCharts / JQuery Code :
<script>
var chart;
$(function() {
var options = {
chart: {
renderTo: 'container',
zoomType: 'xy',
type: 'line'
},
title: {
text: 'Brent Daily Price Curve (FPC as at <cfoutput>#f_date#</cfoutput>)'
},
xAxis: {
labels: {
rotation: 45,
step: 3
},
type: 'category'
},
yAxis: {
lineWidth: 1,
title: {
text: '$ USD'
},
min: 0
},
series: []
};
$.getJSON("brentpricehc_test.cfm?f_date=<cfoutput>#f_date#</cfoutput>", {}, function(jsonResult) {
var BrentUSDPrice = {
name: "Brent Spot (USD)",
type: "line",
data: [],
marker: {
radius: 2
}
};
$(jsonResult).each(function(index) {
BrentUSDPrice.data.push([this.TRADE_DATE, this.BRENT_SPOT]);
});
/*options.series[0] = BrentUSDPrice;*/
options.series.push(BrentUSDPrice);
chart = new Highcharts.Chart(options);
});
});
</script>
I'm unable to plot any values wrt each of the date strings. I tried converting the JSON dates to datetime instead but still the same issue.
Few More details (for testing purposes):
Modifying to the below line plots the graph with the correct "brent_spot" values. This means that the issue lies with the way the "trade_dates" are 'not' plotting.
BrentUSDPrice.data.push([index, this.BRENT_SPOT]);
Edit 2 : (Using Datetime type to make the code work)
JSON Data (New): Returned as TO_CHAR(TRADE_DATE, 'YYYY/MM/DD')
[{"BRENT_SPOT":70.88,"TRADE_DATE":"2009\/07\/31"},{"BRENT_SPOT":73.28,"TRADE_DATE":"2009\/08\/03"},{"BRENT_SPOT":74.31,"TRADE_DATE":"2009\/08\/04"},{"BRENT_SPOT":74.96,"TRADE_DATE":"2009\/08\/05"},{"BRENT_SPOT":74.4,"TRADE_DATE":"2009\/08\/06"},{"BRENT_SPOT":72.84,"TRADE_DATE":"2009\/08\/07"},{"BRENT_SPOT":73.29,"TRADE_DATE":"2009\/08\/10"},{"BRENT_SPOT":72.04,"TRADE_DATE":"2009\/08\/11"}]
$(jsonResult).each(function(index) {
BrentUSDPrice.data.push([new Date(this.TRADE_DATE), this.BRENT_SPOT]);
});
Server side language used : Coldfusion
Database : Oracle
Am I doing something silly somewhere?
I have just tried your code, and it works perfectly fine, see: http://jsfiddle.net/3bQne/1026/
I guess, you need to update to Highcharts 3.0.10 to get this working.
If you are using type: 'category' then you need to assign name: to the data points. See the categories entry at http://api.highcharts.com/highcharts#xAxis
If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highcharts 3.0, categories can also be extracted by giving each point a name and setting axis type to "category".
So the question is whether you are using Highcharts 3.0 and if you do then it needs to look something like this:
data: [{
name: 'Point 1',
color: '#00FF00',
y: 0
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
see: http://api.highcharts.com/highcharts#series.data

Can not see year on graph's x axis that plot by flot

Thanks for those who looked at this post and i would like to post some update with my findings:
This is my javascript to plot a graph on a page by using flot,
var dataSet1 = [[1249102800000, 34.50553], [1249189200000, 27.014463], [1249275600000, 26.7805], [1249362000000, 33.08871], [1249448400000, 51.987762], [1249534800000, 56.868233]];
var dataSet2 = [[1249102800000, 3.405], [1249189200000, 2.701], [1249275600000, 2.678], [1249362000000, 3.308], [1249448400000, 5.187], [1249534800000, 5.668]];
function doPlot(position) {
$.plot($("#placeholder"),
[{ data: dataSet1, label: "Data Set 1" },
{ data: dataSet2, label: "Data Set 2", yaxis: 2}],
{
series: {
lines: { show: true },
points: { show: true }
},
grid: {
hoverable: true,
clickable: true
},
xaxes: [{ mode: 'time',
timeFormat: "%d-%m-%y",
minTickSize: [1, 'day']
}],
yaxes: [{ min: 0 },
{
alignTicksWithAxis: position == "right" ? 1 : null,
position: position
}],
legend: { position: 'sw' }
});
now i am able to get the day and month on the x axis of the graph, but still not years, looks like the timeFormat: "%d-%m-%y" does not have any impacts. Again anyone has any thoughts??
a bit disappointed that no one in here gives me a hint, but of course i fully understand since no one knows everything.
Finally i fixed it by my own effect, and i would like to share my finding in here and hopefully can benefit other folks, here you go:
I need to write a function to format the date, and this is the function
function dateFormatter(v) {
return (new Date(v).toLocaleDateString());
}
this is the x axis that calls that function:
xaxes: [{ mode: 'time',
tickFormatter: dateFormatter,
minTickSize: [1, 'day']
}],
it does achieve what i needed though it is not perfect since the date is like this: Sunday, 2 August 2009, but what i want actually is Aug 2 2009, nevertheless, thsi one: Sunday, 2 August 2009, serves the purpose too.

Categories

Resources