ChartJS date reformatting for use? - javascript

I am having some trouble with my chartjs code. I have a date feed that send data to the charts seen below. While score, and day_7_average worked fine when converting to a list. I am having trouble the dates. the data format I receive is in the "const test" variable and I need it in the "const dates" variable. Based on the nature of the project I can not type them out every time. What is the best way of fixing this problem? thanks.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sentiment</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>
</head>
<style>
.bar { fill: steelblue; }
body { background-color: #1c142c; }
</style>
<body>
<div>
<h1 style="font: 200; color: white;">What are people saying on social media?</h1>
<canvas id="canvas""></canvas>
</div>
</body>
<script>
var ctx = document.getElementById("canvas").getContext('2d');
const test = ['2020-12-24', '2020-12-25', '2020-12-26', '2020-12-27', '2020-12-28', '2020-12-29', '2020-12-30', '2020-12-31']
const dates = ['2020-12-24','2020-12-25','2020-12-26','2020-12-27','2020-12-28','2020-12-29','20201-12-30','2020-12-31']
const score = [-2, -40, 81, -31, 34, -35, -24, -30]
const day_7_average = [0, -6, 3, -2, 5, 5, 0, -7]
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
const colours = score.map((value) => value < 0 ? 'rgb(255, 99, 132)' : 'rgb(75, 192, 192)');
var chartData = {
labels: dates,
datasets: [{
type: 'line',
label: '7 day average',
backgroundColor: 'rgb(201, 203, 207)',
borderColor: 'rgb(201, 203, 207)',
borderWidth: 2,
fill: false,
data: day_7_average,
},
{
type: 'bar',
label: 'Sentiment Score',
backgroundColor: colours,
data: score
}]
};
window.onload = function() {
window.myMixedChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
}
}
});
};

Well... it may be a sloppy workaround but try this:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sentiment</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>
</head>
<style>
.bar { fill: steelblue; }
body { background-color: #1c142c; }
</style>
<body>
<div>
<h1 style="font: 200; color: white;">What are people saying on social media?</h1>
<canvas id="canvas"></canvas>
</div>
</body>
<script>
var ctx = document.getElementById("canvas").getContext('2d');
const test = [''2020-12-24'',
''2020-12-25'',
''2020-12-26'',
''2020-12-27'',
''2020-12-28'',
''2020-12-29'',
''2020-12-30'',
''2020-12-31''];
var i;
dates_tmp = [];
for (i = 0; i < test.length; i++) {
dates_tmp.push(String(test[i].replaceAll("'", "")));
}}
const dates = dates_tmp;
const score = [-2, -40, 81, -31, 34, -35, -24, -30]
const day_7_average = [0, -6, 3, -2, 5, 5, 0, -7]
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
const colours = score.map((value) => value < 0 ? 'rgb(255, 99, 132)' : 'rgb(75, 192, 192)');
var chartData = {
labels: dates,
datasets: [{
type: 'line',
label: '7 day average',
backgroundColor: 'rgb(201, 203, 207)',
borderColor: 'rgb(201, 203, 207)',
borderWidth: 2,
fill: false,
data: day_7_average,
},
{
type: 'bar',
label: 'Sentiment Score',
backgroundColor: colours,
data: score
}]
};
window.onload = function() {
window.myMixedChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
}
}
});
};
</script>
</html>
( Oh and by the way: You've got an unexpected " in line 16 )

Related

ChartJS Doughnut Datasets with different thickness for each data value

I've been using ChartJS with PrimeNG, in Angular. Need to make a doughnut chart with i believe one dataset. I need to make it so each value has a different thickness, like this
So far I've tried a lot of things and read a lot of ChartJS documentation on Doughnut charts, but none of the options have helped me.
Here's how I implement my chart in HTML
<p-chart type="doughnut" [data]="donutData" [options]="donutChartOptions" class="h-10 my-4"></p-chart>
And here's the .ts to it
this.donutData = {
labels: ['A', 'B', 'C'],
datasets: [
{
data: [300, 50, 100],
backgroundColor: ['#F36F56', '#FFC300', '#B8A3FF'],
hoverBackgroundColor: ['#F36F56', '#FFC300', '#B8A3FF'],
},
],
};
this.donutChartOptions = {
cutout: 50,
plugins: {
legend: {
display: false,
labels: {
color: '#ebedef',
},
},
},
};
Here you can find the answer of your question: https://github.com/chartjs/Chart.js/issues/6195
I transferred the answer of "ex47" to chart.js 3
I put the constant "data" into the html file just to have less double code, it should better be in the javascript file.
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<script>
const data = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)"
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)"
],
borderWidth: 1
}
]
}
</script>
<style>
#chartWrapper {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="chartWrapper">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
</body>
<script src="myChart.js"></script>
</html>
myChart.js
var thickness = {
id: "thickness",
beforeDraw: function (chart, options) {
let thickness = chart.options.plugins.thickness.thickness;
thickness.forEach((item,index) => {
chart.getDatasetMeta(0).data[index].innerRadius = item[0];
chart.getDatasetMeta(0).data[index].outerRadius = item[1];
});
}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "doughnut",
plugins: [thickness],
data: data,
options: {
plugins: {
thickness: {
thickness: [[100,130],[80,150],[70,160],[100,130],[100,130],[100,130]],
}
},
}
});
"Spirit04eK"'s solution sets the thickness in descending order of the magnitude of the value
myChart.js
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'doughnut',
plugins: [
{
beforeDraw: function (chart) {
const datasetMeta = chart.getDatasetMeta(0);
const innerRadius = datasetMeta.controller.innerRadius;
const outerRadius = datasetMeta.controller.outerRadius;
const heightOfItem = outerRadius - innerRadius;
const countOfData = chart.getDatasetMeta(0).data.length;
const additionalRadius = Math.floor(heightOfItem / countOfData);
const weightsMap = datasetMeta.data
.map(v => v.circumference)
.sort((a, b) => a - b)
.reduce((a, c, ci) => {
a.set(c, ci + 1);
return a;
}, new Map());
datasetMeta.data.forEach(dataItem => {
const weight = weightsMap.get(dataItem.circumference);
dataItem.outerRadius = innerRadius + additionalRadius * weight;
});
}
}
],
data: data,
options: {
layout: {
padding: 10,
},
plugins: {
legend: false,
datalabels: {
display: false
},
},
maintainAspectRatio: false,
responsive: true,
}
});

How to properly use formatting with chartjs?

I am trying to use formatting in Chart.js. I've configured the imports correctly, but it still doesn't display what I want
It doesn't work on my local pc. I uploaded the same code to codepen and it didn't work either. You can verify it here
var donutEl = document.getElementById("donut").getContext("2d");
var data = [4, 9, 5, 2];
var pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
datasets: [
{
data: [10, 20, 15, 5, 50],
backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
},
],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
plugins: {
datalabels: {
formatter: (value) => {
return value + '%';
}
}
}
}
})
Any ideas what am I doing wrong? Thanks
As described here, you need to register the plugin:
Chart.register(ChartDataLabels);
Live example:
Chart.register(ChartDataLabels);
const donutEl = document.getElementById("donut").getContext("2d");
const data = [4, 9, 5, 2];
const pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
datasets: [{
data: [10, 20, 15, 5, 50],
backgroundColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
}, ],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
plugins: {
datalabels: {
formatter: (value) => {
return value + '%';
}
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<div class="flexWrapper">
<canvas id="donut" width="400" height="400"></canvas>
</div>

I am trying to use the Chartjs-plugin-watermark but it is not working

I've been trying to use the watermark plugin for charts.js. I have successfully downloaded the plugin and uploaded it to Github and created an online version of this file, viewable at: https://cdn.jsdelivr.net/gh/AjaniSt/chartjs-plugin-watermark/chartjs-plugin-watermark.js. However, the plugin is not working. I have tried using a local file instead, putting the "watermark" data in and out of the "plugin" data, and trying the HTML online. However, none have worked. Some guidance would be greatly appreciated. My HTML file is below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/AjaniSt/chartjs-plugin-watermark/chartjs-plugin-watermark.js"></script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="250" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
var imageNew = new Image()
imageNew.src = 'https://image.shutterstock.com/image-vector/hi-hello-banner-speech-bubble-260nw-1505210795.jpg'
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [1880,
1881,
1882,
1883,
1884,
1885,
1886
],
datasets: [{
label: 'Temperature Anomaly',
data: [-0.16,
-0.08,
-0.1,
-0.17,
-0.28,
-0.33,
-0.31
],
fill: true,
backgroundColor: [
'rgba(10, 168, 196, 0.2)',
'rgba(102, 96, 151, 0.2)',
'rgba(57, 87, 255, 0.2)',
'rgba(233, 182, 233, 0.2)',
'rgba(108, 213, 207, 0.2)',
'rgba(125, 178, 230, 0.2)'
],
borderColor: [
'rgba(10, 168, 196, 1)',
'rgba(102, 96, 151, 1)',
'rgba(57, 87, 255, 1)',
'rgba(233, 182, 233, 1)',
'rgba(108, 213, 207, 1)',
'rgba(125, 178, 230, 1)'
],
borderWidth: 1,
pointRadius: 3,
pointHitRadius: 8
}]
},
options: {
scales: {
y: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
return value + '°C';
}
},
title: {
display: true,
text: 'Test'
}
}],
xAxes: [{
ticks: {
maxTicksLimit: 15
}
}]
},
plugins:{
legend: {display: false},
watermark: {
x: 0,
y: 0,
height: 50,
width: 50,
alignX: "top",
alignY: "left",
alignToChartArea: true,
position: "front",
opacity: 1,
image: imageNew,
},
},
onClick: handleClick
}
});
window.onmessage = function(event){
if (event.data && Array.isArray(event.data)) {
myChart.data.datasets[0].data = event.data;
myChart.update();
}
else {
console.log("HTML Code Element received a generic message:");
console.log(event.data);
}
};
function handleClick(e){
var activeBars = myChart.getElementAtEvent(e);
var value = myChart.config.data.datasets[activeBars[0]._datasetIndex].data[activeBars[0]._index];
var label = activeBars[0]._model.label;
window.parent.postMessage({
"type":"click",
"label":label,
"value":value
} , "*");
}
function ready(){
window.parent.postMessage({"type":"ready"}, "*");
}
</script>
</body>
</html>
What looks like the main reason that it's not working is because this plugin was written for V2 and you are using V3, the way you register plugins has changed so you need to change this line which can be found at the bottom of the file: Chart.pluginService.register(watermarkPlugin); to this: Chart.register(watermarkPlugin)
Since this question was posted, chartjs-plugin-watermark 2.0.0 has been released and supports Chart.js 3 and 4. Additionally, the watermark config should be moved from options.plugins.watermark to just options.watermark:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/AlbinoDrought/chartjs-plugin-watermark/chartjs-plugin-watermark.js"></script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="250" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
var imageNew = new Image()
imageNew.src = 'https://image.shutterstock.com/image-vector/hi-hello-banner-speech-bubble-260nw-1505210795.jpg'
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [1880,
1881,
1882,
1883,
1884,
1885,
1886
],
datasets: [{
label: 'Temperature Anomaly',
data: [-0.16,
-0.08,
-0.1,
-0.17,
-0.28,
-0.33,
-0.31
],
fill: true,
backgroundColor: [
'rgba(10, 168, 196, 0.2)',
'rgba(102, 96, 151, 0.2)',
'rgba(57, 87, 255, 0.2)',
'rgba(233, 182, 233, 0.2)',
'rgba(108, 213, 207, 0.2)',
'rgba(125, 178, 230, 0.2)'
],
borderColor: [
'rgba(10, 168, 196, 1)',
'rgba(102, 96, 151, 1)',
'rgba(57, 87, 255, 1)',
'rgba(233, 182, 233, 1)',
'rgba(108, 213, 207, 1)',
'rgba(125, 178, 230, 1)'
],
borderWidth: 1,
pointRadius: 3,
pointHitRadius: 8
}]
},
options: {
scales: {
y: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
return value + '°C';
}
},
title: {
display: true,
text: 'Test'
}
}],
xAxes: [{
ticks: {
maxTicksLimit: 15
}
}]
},
plugins:{
legend: {display: false},
},
watermark: {
x: 0,
y: 0,
height: 50,
width: 50,
alignX: "top",
alignY: "left",
alignToChartArea: true,
position: "front",
opacity: 1,
image: imageNew,
},
onClick: handleClick
}
});
window.onmessage = function(event){
if (event.data && Array.isArray(event.data)) {
myChart.data.datasets[0].data = event.data;
myChart.update();
}
else {
console.log("HTML Code Element received a generic message:");
console.log(event.data);
}
};
function handleClick(e){
var activeBars = myChart.getElementAtEvent(e);
var value = myChart.config.data.datasets[activeBars[0]._datasetIndex].data[activeBars[0]._index];
var label = activeBars[0]._model.label;
window.parent.postMessage({
"type":"click",
"label":label,
"value":value
} , "*");
}
function ready(){
window.parent.postMessage({"type":"ready"}, "*");
}
</script>
</body>
</html>

Chart.js angular8 Y axis ticks

How to dynamically update Y-axis ticks in chart.js. I have tried updating it using the below commands:
this.chartOptions.scales.yAxes[0].ticks.min = 10;
this.chartOptions.scales.yAxes[0].ticks.max = 18;
After changing the chart options, you need to invoke chart.update(). For more details, consult Updating Options from the Chart.js documentation.
Please run the following code sample and press the Update button to see how it works.
function updateYAxis() {
chart.options.scales.yAxes[0].ticks.min = 20;
chart.options.scales.yAxes[0].ticks.max = 100;
chart.update();
}
const chart = new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'My First Dataset',
data: [30, 59, 80],
fill: false,
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
canvas {
max-width: 300px;
}
button {
background-color: #4CAF50;
color: white;
padding: 8px 14px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="10" height="5"></canvas>
<button onclick="updateYAxis()">Update</button>

How to change the label color in chart.js?

I have a pie chart defined like so,
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: data.labels,
datasets: [{
data: data.values,
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 206, 86)',
'rgb(75, 192, 192)',
'rgb(153, 102, 255)',
'rgb(255, 159, 64)',
'rgb(204, 255, 64)',
'rgb(64, 159, 255)',
'rgb(175, 64, 255)'
],
options: {
responsive : true,
}
}],
fontColor : '#FFFFFF'
}
});
how the chart looks,
This however is setting the font color of the labels to black, how can I change this color. Any pointers on this is highly appreciated. Thanks!
You can change the font color of legend­'s label, in the following way ...
options: {
legend: {
labels: {
fontColor: 'white'
}
},
...
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [{
data: [1, 1, 1, 1, 1],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 206, 86)',
'rgb(75, 192, 192)',
'rgb(153, 102, 255)'
]
}]
},
options: {
legend: {
labels: {
fontColor: 'white' //set your desired color
}
}
}
});
canvas{background: #222}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
To change label color with Chart.js, you must set the fontColor.
to set the fontColor of the labels by setting the fontColor in the options object property.
for example;
fontColor: "white", // set color
or you can visit the following link : https://thewebdev.info/2022/06/27/how-to-change-label-color-with-chart-js-and-javascript/
Sorry to unbury this but trying any solutions and only this works. create plugin before chart :
Chart.plugins.register({
beforeDraw: function(c) {
c.legend.options.labels.fontColor = 'hsl(0,0%,85%)';
}
});
var chart = new Chart(ctx, {
....
The only solution i found to work for this problem is the following line
Chart.defaults.color = '#fff';
Hope it helps

Categories