Chart.js - Timeline - javascript

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>

Related

Counting string to plot a graph using chart.js and angular

I am trying to create a bar chart in angular using chart.js and angular.
I want to display the disaters vs area. with the type of disaster ( earthquake, hurricane, storm...etc) on the x-axis and area (as in location) on the y-axis.
However, the area data is string and does not work when trying to plot a bar graph as it requires numbers.
I am reading the data as follows:
ngOnInit(): void {
this.chartService.noOfEqu().subscribe((res) => {
let area = res.map((res) => res.area);
let disaster = res.map((res) => res.disasterNature);
new Chart('disasterCanvas', {
type: 'bar',
data: {
labels: disaster,
datasets: [
{
data: area,
label: 'area',
backgroundColor: '#A121D5',
},
],
},
options: {
plugins: {
legend: {
display: true,
},
},
scales: {
x: {
ticks: {
display: true,
},
},
y: {
ticks: {
display: true,
},
},
},
},
});
});
}
}
Where let area = res.map((res) => res.area); is the area variable.
I want to know what is the best way to structure the data to be entered into the graph.
The disaster data that is logged is:
and the area data :
How can i structure the area such that it counts how much areas that a disaster has occured and plot it on the bar chart?
Thank you in advance...if there is anything i can clarify please let me know in the comments
Also is there another way to display this data besides tallying the string data?
You need to add a labels array to the scale and set the type to category to use string data:
const options = {
type: 'bar',
data: {
labels: ["Earthquake", "Tornade", "Flood"],
datasets: [{
label: '# of Votes',
data: ['Paris', 'Berlin', 'London'],
backgroundColor: 'pink'
}]
},
options: {
scales: {
y: {
type: 'category',
reverse: true,
labels: ['', 'London', 'Paris', 'Berlin']
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

chart.js plotting timeseries

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>

Dynamic stacked column in CanvasJS

How can I create a stacked column chart with dynamic data?
For example, I have an external JSON object like:
[
{
id : ‘ID123’,
occurrences: [5,6,8],
description: ["Hours spent working", "Hours spent skiing", "Hours spent studying"]
},
{
id : ‘ID456’,
occurrences: [7,2,12],
description: ["Hours spent working", "Hours spent skiing", "Hours spent studying"]
}
]
How do I make it so there would be two stacked columns using the id as the label and the array of occurrences is used to build the stacked column on top of each label?
Edit:
Added representation of how graph should look
I would suggest using chart.js for this as it will be much easier than building it out yourself. Here is a example using the data you provided.
var barChartData = {
labels: ['ID123', 'ID456'],
datasets: [{
label: 'Hours spent working',
backgroundColor: '#FF0000',
data: [
5,
7
]
}, {
label: 'Hours spent skiing',
backgroundColor: '#00FF00',
data: [
6,
2
]
}, {
label: 'Hours spent studying',
backgroundColor: '#0000FF',
data: [
8,
12,
]
}]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

ChartJS: Horizontal Bar with multiple datasets not showing Bars

I have Horizontal Bar comparing Rooms & Guests target vs achieved.
Rooms has 3 data values (Available, Budget, Actual) and Guests has only 2 (Budget, Actual).
Below is the code generates the chart:
data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [5580]
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500]
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245]
}];
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data
}
}
Issue with the above code is, Rooms Budget bar is not showing up.
It shows only when I add [5580,0] to the Guests Available data value; however there is no such Data for Guests like Rooms.
Here is the JSFiddle (https://jsfiddle.net/kingBethal/vtf17k84/8/).
5000 is the lowest value in your dataset and Chart.js is creating its scale starting at 5000:
Set the beginAtZero property to true and you'll see the expected bar:
let data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [5580]
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500]
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245]
}];
let myChart = new Chart(document.getElementById('chart'), {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>

Charts.js: changing xAxis time attribute with function

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();
};

Categories

Resources