How to use canvasjs to draw column chart using text data - chart.js

I am using the canvasjs for plotting the column chart. I am using the code from this link https://canvasjs.com/editor/?id=https://canvasjs.com/example/gallery/column/oil_reserves/, the code is below:
<!DOCTYPE HTML>
<html>
<head>
<title>Basic HTML5 Column Chart </title>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Oil Reserves"
},
animationEnabled: true,
axisY: {
title: "Reserves(MMbbl)"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "MMbbl = one million barrels",
dataPoints: [
{y: 297571, label: "Venezuela"},
{y: 267017, label: "Saudi" },
{y: 175200, label: "Canada"},
{y: 154580, label: "Iran"},
{y: 116000, label: "Russia"},
{y: 97800, label: "UAE"},
{y: 20682, label: "US"},
{y: 20350, label: "China"}
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
Now I want to use a text file generated from python instead of the default values in the dataPoints. The test file data looks like a dictionary data separated by comma. Here is a sample of the text file data:
{'DNS_SERVER1': 2.768651, 'FTP_SERVER1': 2.488129, 'AUTHENTICATION_SERVER1': 2.768651, 'WAP_SERVER1': 2.768651, 'WEB_SERVER1': 2.768651, 'EMAIL_SERVER1': 2.768651}
I want the labels to be first part before semicolon like 'DNS_SERVER1' and the value y to be equal to 2nd part of the semicolon like 2.768651. How Can I do this using the canvasjs script? Any help is appreciated.
Thanks.

You must have to read the file to two separate datasets (LABELS and DATA) and insert them like this:
data = {
labels: ["DNS_SERVER", "FTP_SERVER", "AUTH_SERVER"],
datasets: [{
label: 'Performance',
data: [2.768651, 2.488129, 2.768651]
}]
};
Above is a nominal way.
You can change "labels:" dataset and "data:" dataset for your loaded data.

Related

Chart.js no data displayed with predefined units

I want to display values with predefined units. e.g.: 22.00B/s
The data structure looks like this:
['6.84KB/s', '4.49KB/s', '3.42KB/s']
But only such data are displayed:
['7.5', '4.3', '10.3']
How can I display such values?
3.42KB/s
(Without removing letters or special characters)
You will need to use a category scale for this:
const options = {
type: 'bar',
data: {
labels: ["val1", "val2", "val3"],
datasets: [{
label: '# of Votes',
data: ['6.84KB/s', '4.49KB/s', '3.42KB/s'],
backgroundColor: 'pink'
}]
},
options: {
scales: {
y: {
type: 'category',
labels: ['6.84KB/s', '4.49KB/s', '3.42KB/s'],
reverse: true
}
}
}
}
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.8.2/chart.js"></script>
</body>

Horizontal floating bars with a time y-axis in Chart.js

I'm trying to adapt https://www.chartjs.org/docs/latest/samples/bar/floating.html to create a kind of timeline chart, where the horizontal axis (the range data) are timestamps. Unfortunately I can't seem to get the data to display, and don't see any error messages, etc.
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment#^1"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
</body>
<script>
//const labels = ["a","b","c","d","fff","g","h"]
const labels = ["a","b"]
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: [[moment("2021-11-23T00:24:14Z"),moment("2021-11-23T00:34:03Z")],
[moment("2021-11-23T00:24:14Z"),moment("2021-11-23T00:26:35Z")]]
// This works fine (without 'yAxes' below):
//data: labels.map(() => {
//return [Math.random(), Math.random()];
//}),
//backgroundColor: Utils.CHART_COLORS.red,
},
]
};
const config = {
type: 'bar',
data: data,
options: {
yAxes: [{
type: 'time',
}],
indexAxis: 'y',
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Floating Bar Chart'
}
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
</script>
</html>
EDIT: JSFiddle: https://jsfiddle.net/r5ypuvks/
Mmm it seems my issues are:
not using proper axis format for chart.js 3
need to scale the graph myself
need to refer to horizontal axis as x
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment#^1"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
</body>
<script>
//const labels = ["a","b","c","d","fff","g","h"]
const labels = ["a","b"]
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: [[("2021-11-23T00:24:14Z"),("2021-11-23T00:34:03Z")],
[("2021-11-23T00:25:14Z"),("2021-11-23T00:26:35Z")]]
// This works fine (without 'yAxes' below):
//data: labels.map(() => {
//return [Math.random(), Math.random()];
//}),
//backgroundColor: Utils.CHART_COLORS.red,
},
]
};
const config = {
type: 'bar',
data: data,
options: {
scales: {
x: {
min: ("2021-11-23T00:20:14Z"),
max: ("2021-11-23T00:44:14Z") ,
type: 'time',
},
},
indexAxis: 'y',
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Floating Bar Chart'
}
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
</script>
</html>

donut chart not rendering with csv data chart.js

I am trying to create a donut chart with chart.js using data from csv file. Following is my script so far, but it is not working. Any guidance is appreciated on the same.
<script>
var file='donut.csv';
d3.csv(file).then(makeChart); //use d3.csv to read file
function makeChart(types){
var can=types.map(function(d){return d.cancelled});
var suc=types.map(function(d){return d.success});
var fa=types.map(function(d){return d.failed});
{
var chart=new Chart(document.getElementById("doughnut-chart"), {
type: 'doughnut',
data: {
labels: ["Cancelled","Success", "Failed"],
datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#3cba9f","#8e5ea2"],
data: [can,suc,fa]
}
]
},
options: {
title: {
display: true,
text: 'Weekly Status'
}
}
}
}
);
</script>
and my donut.csv looks like as below:
cancelled,300,
success,1000,
failed,20,
Since your CSV data has no header, you should use d3.text to load the data, followed by d3.csvParseRows to parse it to a JSON array (see https://stackoverflow.com/a/13870360/2358409). To extract the data values from the JSON array, you can use Array.map.
data: d3.csvParseRows(types).map(v => v[1])
Please take a look at your amended code and see how it works.
d3.text("https://raw.githubusercontent.com/uminder/testdata/main/so/csv/donut.csv").then(makeChart);
function makeChart(types) {
new Chart('doughnut-chart', {
type: 'doughnut',
data: {
labels: ['Cancelled', 'Success', 'Failed'],
datasets: [{
label: 'Population (millions)',
backgroundColor: ['#3e95cd', '#3cba9f', '#8e5ea2'],
data: d3.csvParseRows(types).map(v => v[1])
}]
},
options: {
title: {
display: true,
text: 'Weekly Status'
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="doughnut-chart" height="90"></canvas>

Chartjs Polar Area Chart: Category missing

I just can't figure out why is there allways at least one category missing from my chart:
This does not happen when I switch chart type to type:'pie'.
Please find my code below:
<!DOCTYPE html>
<html>
<body>
<div style="width: 40%;">
<canvas id="polarAreaChart " width="400" height="400"></canvas>
</div>
<script>
var ctx = document.getElementById("polarAreaChart ");
var polarAreaChart = new Chart(ctx, {
type: 'polarArea',
options: {
legend: {
display: true,
position: 'bottom',
}
},
data: {
labels: ["D1","D2","D3"],
datasets: [{
label: 'Dimensiones',
data: [40, 20, 40],
backgroundColor: [
"#f8b195",
"#c06c84",
"#6c5b7b"
]
}]
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
</body>
</html>
Any comments will help.
Cheers!
Apparently it was just a bug.
Solved it by using a more recent version of Chartjs:
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js

Chart.js - scaleType='date' not working

Using Chart.js, I'm trying to get the x-axis (and toolips) to show a DATE, but all I can get are large integers appearing as the x-axis label. I've compared what the example in the documentation does and I don't see what it's doing that i'm not. Can anyone please help?
Here's the tiny example that I created showing it not working.
(btw - as a side issue, notice that if the color of the RED line is spelled Red rather than red, the line looks normal, but tooltips no longer work on that line)
https://plnkr.co/edit/CKUf4zFC1vhe3VNUF5Lf?p=preview
javascript for the above plunker example is below
----------------------------------------------------
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<canvas id="canvas"></canvas>
<script>
var chartData = {
datasets: [{
borderColor: 'Red',
label: 'Capital R in borderColor, tooltips dont work',
data: [{
x: new Date('2011-04-11T11:45:00'),
y: 25
}, {
x: new Date('2011-04-11T12:51:00'),
y: 28
}, {
x: new Date('2011-04-11T14:10:00'),
y: 22
}, {
x: new Date('2011-04-11T15:15:00'),
y: 18
}]
}, {
borderColor: 'green',
label: 'borderColor all lower case, tooltips now work',
data: [{
x: new Date('2011-04-11T11:45:00'),
y: 15
}, {
x: new Date('2011-04-11T12:51:00'),
y: 18
}, {
x: new Date('2011-04-11T14:10:00'),
y: 12
}, {
x: new Date('2011-04-11T15:15:00'),
y: 8
}]
}, ]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myScatterxx = Chart.Scatter(ctx, {
data: chartData,
scaleType: 'date',
options: { title: { display: true, text: "scaleType='date' isn't working", fontSize:36} },
});
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js">
</script>
</body>
</html>
First of all, since the documentation is messy, I'm not surprised you didn't get how to create a time-scale chart. The actual call is the following :
window.myScatterxx = Chart.Scatter(ctx, {
data: chartData,
options: {
title: {
display: true,
text: "it is now working",
fontSize: 36
},
scales: {
xAxes: [{
// This is the important part
type: "time",
}]
}
},
});
Now you have the correct syntax, you'd need to import the correct library as well. As I can see in the piece of code you gave, you imported Chart.min.js, but you need more since you know work with the time element.
You can either :
Import Moment.js (CDN link) and then Chart.min.js.
Import Chart.bundle.min.js, that contains both Moment and Chart libraries.
Finally, I also noticed in your code you had a problem displaying tooltips for the red dataset. It is because you defined its color as Red. Change it to red and tooltips will work again :
datasets: [{
borderColor: 'red',
label: 'Capital R in borderColor, tooltips now work',
data: [
// ...
]
}]
You can see all these fixes live in this jsFiddle, and here is the final result :