I have a chart built with the Charts.js api. The x axis is configured to show ticks on the hour via moment.js. I would like to give the option to change the X axis ticks from hour to days in the week: I know that to do this I just have to change the code in the Chart from this:
xAxes:
[{
type: 'time',
distribution: 'linear',
time:
{
unit: 'hour'
}
}],
To this:
xAxes:
[{
type: 'time',
distribution: 'linear',
time:
{
unit: 'week'
}
}],
But I can't get it to happen with a JavaScript function. I would like to be able to change this setting according to preferences, so I want to build a function that when called will change the "unit" attribute to something different. Can anyone help? Here is what I have so far:
function setXAxis()
{
chart.config.options.scales.xAxes.time.unit.push('week');
chart.update();
};
Complete chart.js code:
// Setting up progress chart via Charts.js
var ctx = document.getElementById("myChart").getContext("2d");
Chart.defaults.global.defaultFontColor = "#58a7dd";
// Configuration
var chart = new Chart(ctx,
{
type: 'line',
data:
[{
x: new Date(),
y: 1
},
{
t: new Date(),
y: 10
}],
options:
{
scales:
{
xAxes:
[{
type: 'time',
distribution: 'linear',
time:
{
unit: 'hour' //THIS IS WHAT I WANT TO CHANGE WITH THE FUNCTION
}
}],
yAxes:
[{
type: 'category',
labels: ['one', 'two', 'three', 'four', 'five']
}]
}
}
});
You can Update the options of a chart directly with its options key, not with config.options also unit is not array to push, its a key so assign value to it
in your code
function setXAxis()
{
chart.options.scales.xAxes[0].time.unit='week';
chart.update();
};
Related
I am trying to display dates on xAxes with Chart.js
I tried this with 2 dates but it shows nothing.
Probably something I did wrong with the labels or date format.
<canvas id="graph"></canvas>
<script>
var ctx = document.getElementById('graph').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["2013-02-08", "2013-02-10"],
datasets: [{
label: "Something",
data: [{
x: "2013-02-08",
y: 1
}, {
x: "2013-02-10",
y: 10
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}]
}
}
});
</script>
Need help :)
Your code looks fine except that you don't need to define data.labels since the data in your dataset is defined as individual points through objects containing x and y properties.
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.
var ctx = document.getElementById('graph').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Something",
data: [
{ x: "2013-02-08", y: 1 },
{ x: "2013-02-10", y: 10 }
]
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="graph"></canvas>
Attempting to pass through data from django to a webpage to render a responsive chart. The data are being passed correctly to js, but I am driving myself crazy trying to understand why charts.js is throwing an error.
I have hardcoded some data for example:
function setLineChart() {
var ctx = document.getElementById("myLineChart").getContext('2d');
var dat_1 = {
label: 'things',
borderColor: 'blue',
data: [
{t: new Date("04/01/2020"), y: 310},
{t: new Date("04/02/2020"), y: 315},
{t: new Date("04/03/2020"), y: 320},
]
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [dat_1]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
},
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
}
<canvas id="myLineChart" width="600" height="600"></canvas>
And this returns a Uncaught TypeError: Cannot read property 'skip' of undefined error that I can't debug. setLineChart() gets called as part of an ajax response on a form update. When I comment out the options section, it does render a chart, but misses off the last data point, and has undefined as the x-axis marker.
Any help would be appreciated.
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.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
This will solve your problem as the following amended code snippet illustrates.
var ctx = document.getElementById("myLineChart").getContext('2d');
var dat_1 = {
label: 'things',
borderColor: 'blue',
data: [
{ t: new Date("04/01/2020"), y: 310 },
{ t: new Date("04/02/2020"), y: 315 },
{ t: new Date("04/03/2020"), y: 320 },
]
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [dat_1]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
},
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myLineChart" height="90"></canvas>
I am trying to create a gantt chart with Chart.js. I use horizontalBar chart type and this works fine if I populate numbers instead of dates, but it does not render when I pass dates as data.
Data structure: Task, Start Date, End Date
this.chartData = {
labels: ['Task 1', 'Task 2'],
datasets: [{
data: ['2019-01-20', '2019-01-30'],
}],
};
this.options = {
title: {
display: true,
text: 'Title of Chart',
},
legend: {display: false},
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
},
}],
},
};
Template:
<chart class="chart" type="horizontalBar" [data]="chartData" [options]="options"></chart>
Tried another example
You are passing the values as strings. Try to pass as dates:
datasets: [{
label: 'Demo',
data: [{
t: new Date("2015-3-15 13:3"),
y: 12
},
I am trying to plot a bar chart with multiple datasets on a time series, however some of the data gets lost along the way.
for simplicity I have removed the ajax call and plotted some data:-
var config = {
type: 'bar',
data: {
datasets: [{
label: "Dataset 1",
data: [{
x: new Date('2017-03-01'),
y: 1
}, {
x: new Date('2017-03-02'),
y: 2
}, {
x: new Date('2017-03-03'),
y: 3
}, {
x: new Date('2017-03-04'),
y: 4
}],
backgroundColor: "red"
}, {
label: "Dataset 2",
data: [{
x: new Date('2017-03-01'),
y: 1
}, {
x: new Date('2017-03-02'),
y: 2
}, {
x: new Date('2017-03-03'),
y: 3
}, {
x: new Date('2017-03-04'),
y: 4
}],
backgroundColor: "blue"
}]
},
options: {
scales: {
xAxes: [{
type: "time",
time: {
unit: 'day',
round: 'day',
displayFormats: {
day: 'MMM D'
}
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
using the above configuration dataset 1 point 1 and dataset 2 point 4 (so basically the first and last points) do not get drawn.
Any ideas where I am going wrong here?
Also I am using this time series version because I was hoping to have "gaps" in the chart, for example dataset 1 might have a series for 2017-03-01 and dataset 2 might not, in this case dataset 2's next date will bunch up to dataset 1's making it look like it does belong to that date.
Any help would be appreciated
I had the exact same issue when displaying a bar chart with time as the X axes.
Inside your xAxes you need to add an additional configuration option:
xAxes: [{
offset: true
}]
Description from the ChartJS documentation:
If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to true in the bar chart by default.
ChartJS Documentation Cartesian
I have large collection of data in the format [1421065200000, 1.72], where the first parameter is time in milliseconds and the second parameter is the value at that specific time. I have data array consisting of such data in large size. Now I want scrollable graph containing plot of such time and value data. Here is my javascript implementation to do so,
var dataArray; //This contains my data array i.e. ([[t1, v1],[t2, v2],...])
var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];
var chartOption = {
chart: {
type: graphType,
renderTo: 'graph-container',
zoomType: 'x',
useUTC: false
},
title: {
text: 'Data from last 24 hours'
},
credits : {
enabled: false
},
xAxis: {
title: {
text: null
},
type: 'datetime',
dateTimeLabelFormats: {
second: '%Y-%m-%d<br/>%H:%M:%S',
minute: '%Y-%m-%d<br/>%H:%M',
hour: '%Y-%m-%d<br/>%H:%M',
day: '%Y<br/>%m-%d',
week: '%Y<br/>%m-%d',
month: '%Y-%m',
year: '%Y'
},
allowDecimals: false,
ordinal: false,
min: minDate,
max: maxDate
},
yAxis: {
title: {
text: null
}
},
plotOptions: {
series: {
pointStart: minDate,
pointInterval: 5 * 60 *1000
}
},
series: [{
name: parameterName,
data: dataArray
}],
exporting: {
enabled: false
}
};
parameterChart = new Highcharts.Chart(chartOption);
}
The chart shows incorrect data, the time value on x-axis doesn't match the value at y-axis. What is the most correct and efficient to show such time series. Should I use Highcharts or Highstock. Please guide me through this, with suggestion or maybe with solution.
What I did was, I used HighStock instead of HighCharts (since I needed scrollbar along x-axis for large collection of data). I was passing the date in my local time zone format, whereas the chart was using UTC. So, I disabled the use of UTC (alternative: I could have provided data in UTC and drawn the graph using the same, In my case I needed my local labels). I gave the minimum and maximum range to the x-axis through x-axis min and max configuration. Here is the sample of my code,
//dataArray contains the array of data [[x1, y1], [x2, y2], ...]
//x is Date, y is temperature value (say)
var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];
//Disable use of UTC
Highcharts.setOptions({
global: {
useUTC: false
}
});
//Create graph options
var chartOption = {
chart: {
type: graphType, //line, bar, column, etc
renderTo: 'graph-container', //div where my graph will be drawn
zoomType: 'x' //Making x-axis zoomable/scrollable
},
title: {
text: 'Data from last 6 hours'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Pinch the chart to zoom in'
},
xAxis: {
title: {
text: null
},
type: 'datetime', //For time series, x-axis labels will be time
labels: {
//You can format the label according to your need
format: '{value:%H:%m}'
},
min: minDate,
max: maxDate,
minPadding: 0.05,
maxPadding: 0.05
},
yAxis: {
title: {
text: null
}
},
scrollbar: {
enabled: true
},
series: [{
name: "Temperature", //Name of the series
data: dataArray
}],
exporting: {
enabled: false
},
credits : {
enabled: false
}
};
//Finally create the graph
var myChart = new Highcharts.Chart(chartOption);