Chart.js no data displayed with predefined units - chart.js

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>

Related

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

Using CSS variables (color) with chart.js - "var(--primaryColor)" not working

I've got a web-app project that uses two stylesheets to define two color sets (day & night mode). Each stylesheet defines the same CSS variables with different colors (e.g. "--primaryColor: 'white'" in dayMode.css and "--primaryColor: 'black'" in nightMode.css. The stylesheet is toggled when clicking a button.
Now, all elements are colored by referring to these variables - both in the CSS and JS code. For example:
div {background-color: var(--primaryColor);}
$(this).css({backgroundColor: "var(--primaryColor)"});
When switching the stylesheet, all elements adjust to the new definitions. Now I set up my very first Chart.js and tried to color it with my variables, like:
yAxes: [{
ticks: {
fontColor: "var(--primaryTextColor)"
}
}]
But that doesn't work. Any idea how to fix this? Thanks in advance!
CSS variables are used in stylesheet, if you would access them in JS you can do like below snippet:
var style = getComputedStyle(document.body);
var primCol = style.getPropertyValue('--primaryColor');
$("#mydiv").text("primaryColor: " + primCol);
:root {
--primaryColor: #336699;
}
#mydiv {
background-color: var(--primaryColor);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
</div>
So in a chart.js:
var style = getComputedStyle(document.body);
var primCol = style.getPropertyValue('--primaryColor');
var chartCol = style.getPropertyValue('--chartColor');
var chartData = {
labels: ['a', 'b', 'c', 'd'],
datasets: [{
label: 'value',
backgroundColor: 'rgba(219, 20, 0, 0.2)',
borderColor: chartCol,
data: [30, 50, 25, 10]
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
legend: { display: false },
scales: {
yAxes: [{
ticks: {
fontColor: primCol,
}
}],
xAxes: [{
ticks: {
beginAtZero: true
}
}],
}
}
});
:root {
--primaryColor: #00ff00;
--chartColor: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myChart" height="300" width="500"></canvas>

How to use canvasjs to draw column chart using text data

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.