Related
This question already has an answer here:
How do I show labels along with lines in Chart.js v3? [duplicate]
(1 answer)
Closed last month.
Like this one:
The label property in datasets is not working and shows nothing:
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
The complete code is given below:
<!DOCTYPE html>
<html>
<head>
<title> Example</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.1/chart.min.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
legend: {
display: false
}
}
});
</script>
</body>
</html>
Well if a plugin like https://www.chartjs.org/chartjs-plugin-annotation/2.0.0/ doesn't solve the problem (Check out this answer for a demo), I would write my own specific plugin, that draws on the chart, after rendering was completed (see demo below for details).
And to be on the save side, I would add some padding to the right of the chart, to prevent a cut off, as done in the demo (link to the documentation).
Here a demo, how a very basic plugin could like:
(chart data from the question)
var miniLabelPlugin = {
id: 'miniLabelPlugin',
afterRender: function(chart, args, options) {
const { ctx } = chart;
chart.config.data.datasets.forEach((dataSet, index) => {
let lastPoint = chart.getDatasetMeta(index).data[chart.getDatasetMeta(index).data.length - 1];
let lastValue = dataSet.data[dataSet.data.length -1]
console.info(dataSet.data, lastPoint)
ctx.fillStyle = options.textColor;
ctx.font = options.font;
ctx.fillText(`${lastValue}`, lastPoint.x + options.paddingLeft, lastPoint.y);
});
},
defaults: {
paddingLeft: 10,
font: "10px Arial",
textColor: "black"
}
}
const config ={
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [28, 48, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}]
},
// here the plugin is added to the chart
plugins: [miniLabelPlugin],
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins:{
legend: {
display: false
},
},
layout: {
padding: {
right: 50
}
}
}
};
new Chart(
document.getElementById('chart'),
config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>
<div class="chart" style="height:184px; width:350px;">
<canvas id="chart" ></canvas>
</div>
For static labels you need to add "animation" key like
import {
Chart,
Sample
} from "chart.js";
import {
map
} from "lodash";
import {
data
} from "../data";
var ctx = document.getElementById("myChart");
const d = map(data, (data, index) => {
return {
data: [data],
backgroundColor: "blue",
pointRadius: 2,
fill: "start"
};
});
const dd = map(data, data => {
return data.y;
});
console.log(dd);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Line 1',
data: [6, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2
},
{
label: 'Line 2',
data: [5, 20, 40, 19, 86, 27, 90],
backgroundColor: 'rgba(153, 102, 255, 0.2)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 2
}
]
},
options: {
animation: {
onComplete: function() {
const chartInstance = myChart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(
18,
Chart.defaults.global.defaultFontStyle,
Chart.defaults.global.defaultFontFamily
);
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.data.datasets.forEach(function(dataset, i) {
const meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
const data = dataset.data[index];
ctx.fillStyle = "#000";
ctx.fillText(data, bar._model.x, bar._model.y - 2);
});
});
}
},
tooltips: {
enabled: true
},
scales: {
y: {
beginAtZero: true
}
},
legend: {
display: false
}
}
});
Goodluck!
How make border radius for chart area chart.js
I need to make a border radius of 16px for the chart area
Maybe there is a plugin?
I am using chart.js V3.7.
I am using chart.js V3.7
How make border radius for chart area chart.js
I need to make a border radius of 16px for the chart area
Maybe there is a plugin?
I am using chart.js V3.7.
const ctx = document.getElementById('myChart').getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 400)
gradient.addColorStop(0, 'rgba(244, 192, 56, 0.3)')
gradient.addColorStop(0.35, 'rgba(244, 192, 56, 0.3)')
gradient.addColorStop(1, 'rgba(244, 192, 56, 0)');
const plugin = {
id: 'background',
beforeDraw: (chart, args, opts) => {
if (!opts.color) {
return;
}
const {
ctx,
chartArea
} = chart;
ctx.fillStyle = opts.color;
ctx.fillRect(chartArea.left, chartArea.top, chartArea.width, chartArea.height)
}
};
Chart.register(plugin);
var config = {
type: 'line',
data: {
labels: [['05.08', '2021'], ['06.08', '2021'], ['07.08', '2021'], ['08.08', '2021'], ['09.08', '2021'], ['10.08', '2021'], ['11.08', '2021'], ['12.08', '2021'], ['13.08', '2021'], ['14.08', '2021'], ['15.08', '2021']],
datasets: [{
data: [130, 260, 240, 270, 249, 310, 295, 330, 247, 280, 265, 265,],
fill: true,
backgroundColor: gradient,
borderColor: [
'#F4C038',
],
borderWidth: 4,
pointRadius: 6,
pointBackgroundColor: '#272E3B',
pointHoverBorderColor: '#fff',
pointBorderWidth: 4,
pointHoverBorderWidth: 4,
}]
},
options: {
responsive: true,
tension: 0.25,
plugins: {
background: {
color: '#272E3B'
},
legend: {
display: false,
labels: {
font: {
size: 14,
family: "Rubik"
}
}
}
},
scales: {
y: {
grid: {
color: '#3D4554',
borderColor: '#3D4554',
tickColor: 'transparent',
},
ticks: {
padding: 38,
callback: function(value) {
return '$' + value;
},
color: "rgba(255, 255, 255, 0.5)",
font: {
size: 16,
family: "Rubik",
weight: 300
},
}
},
x: {
grid: {
color: '#3D4554',
borderColor: '#3D4554',
tickColor: 'transparent',
},
ticks: {
padding: 16,
color: "rgba(255, 255, 255, 0.5)",
font: {
size: 14,
family: "Rubik",
weight: 300
},
}
}
},
}
};
new Chart(ctx, config);
There is no plugin but you can write your own like so:
const plugin = {
id: 'border',
beforeDraw(chart, args, options) {
const {
ctx,
chartArea: {
left,
top,
width,
height
}
} = chart;
ctx.save();
ctx.strokeStyle = options.color;
ctx.lineWidth = options.width;
ctx.setLineDash(options.dash || []);
ctx.lineDashOffset = options.offset;
ctx.strokeRect(left, top, width, height);
ctx.restore();
}
};
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'pink'
}
]
},
options: {
plugins: {
border: {
color: 'red',
width: 16
}
}
},
plugins: [plugin]
}
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.0/chart.js"></script>
</body>
To add the border to the chart area in chart.js, we need to use the chartAreaBorder plugin
const chartAreaBorder = {
id: 'chartAreaBorder',
beforeDraw(chart, args, options) {
const {ctx, chartArea: {left, top, width, height}} = chart;
ctx.save();
ctx.strokeStyle = options.borderColor;
ctx.lineWidth = options.borderWidth;
ctx.setLineDash(options.borderDash || []);
ctx.lineDashOffset = options.borderDashOffset;
ctx.strokeRect(left, top, width, height);
ctx.restore();
}
};
Paste the above piece of code before creating your chart and
Then use the following code for creating your chart and border around it,
const ctx = document.getElementById('dynamic-chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'Your_Chart_Type_Here',
data: {
labels:Your_Data_Here,
datasets: [{
label: 'Your Data Here',
data: 'Your_Data_Here,
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
}]
},
options: {
plugins:{
chartAreaBorder:{
borderColor:'red',
borderWidth:2,
borderDash:[5,5],
borderDashOffset:2,
}
}
}
},
plugins:[chartAreaBorder]
});
Result is as follow
This Code will give the border to chartArea. I hope this sorted out your problem.
I'm passing the following config to Chart.js:
{
type: 'doughnut',
data: {
labels: ['a', 'b', 'c'],
datasets: [{
data: [878, 19020, 100412286],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)'
],
hoverOffset: 4
}]
}
}
But because of the huge difference between all three (given how much bigger c is), c ends up "overlapping" everything else and I just get a doughnut with only one color, showing only c.
If I try a smaller value for c all three sectors show up fine.
But I don't understand, Chart.js should've been able to show all pieces (set a minimum size for the smallest sector etc.)
Is there some parameter I can pass to the config to fix this ?
You can use a logarithmic scale but only for lines. A donut is not a good choice for your use case
https://www.chartjs.org/docs/latest/samples/scales/log.html
Config:
const config = {
type: 'line',
data: data,
options: {
responsive: true,
plugins: {
title: {
display: true,
text: 'Chart.js Line Chart - Logarithmic'
}
},
scales: {
x: {
display: true,
},
y: {
display: true,
type: 'logarithmic',
}
}
},
};
Setup:
const DATA_COUNT = 7;
const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100};
const labels = Utils.months({count: 7});
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: logNumbers(DATA_COUNT),
borderColor: Utils.CHART_COLORS.red,
backgroundColor: Utils.CHART_COLORS.red,
fill: false,
},
]
};
Action
const logNumbers = (num) => {
const data = [];
for (let i = 0; i < num; ++i) {
data.push(Math.ceil(Math.random() * 10.0) * Math.pow(10, Math.ceil(Math.random() * 5)));
}
return data;
};
const actions = [
{
name: 'Randomize',
handler(chart) {
chart.data.datasets.forEach(dataset => {
dataset.data = logNumbers(chart.data.labels.length);
});
chart.update();
}
},
];
One alternative is using 3 datasets, one for each data.
labels: ['a', 'b', 'c'],
datasets: [
{
label: "My First Dataset",
data: [878,0,0],
backgroundColor: [
"rgb(255, 205, 86)",
"rgb(255, 99, 132)",
"rgb(54, 162, 235)",
],
offset:0,
hoverOffset: 0,
},
{
label: "My First Dataset2",
data: [0,19020,0],
backgroundColor: [
"rgb(255, 205, 86)",
"rgb(255, 99, 132)",
"rgb(54, 162, 235)",
],
offset:0,
hoverOffset: 0,
},
{
label: "My First Dataset2",
data: [0,0,100412286],
backgroundColor: [
"rgb(255, 205, 86)",
"rgb(255, 99, 132)",
"rgb(54, 162, 235)",
],
offset:0,
hoverOffset: 0,
},
],
I hope this help.
Given my chartJS config below
var ctx = document.getElementById('myChart').getContext('2d');
Chart.defaults.global.defaultFontColor = 'rgba(255, 255, 255, 1)';
Chart.defaults.global.defaultFontFamily = 'Arial';
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Investment', 'Sustainable'],
datasets: [{
label: 'myLabel',
data: [11, 5],
backgroundColor: [
'rgba(234, 82, 4, 0.2)',
'rgba(0, 121, 109, 0.2)'
],
borderColor: [
'rgba(234, 82, 4, 1)',
'rgba(0, 121, 109, 1)'
],
borderWidth: 1
}]
},
options: {
legend: {
labels: {
display: true
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
gridLines: {
color: 'rgba(255, 255, 255, 0.1)'
},
scaleLabel: {
display: true,
},
}],
}
}
});
I need to get something as close as the following
Using Quickchart API, I am submitting the config through the URL, but I am having trouble setting the labels color? options:{legend:{labels:{fontColor: 'white'}},
https://quickchart.io/chart?c={type:%27bar%27,data:{labels:[%27Investment%27,%27Sustainable%20%27],datasets:[{label:%27myLabel%27,data:[11,5],backgroundColor:%20[%27rgba(234,%2082,%204,%200.2)%27,%27rgba(0,%20121,%20109,%200.2)%27],borderColor:%20[%27rgba(234,%2082,%204,%201)%27,%27rgba(0,%20121,%20109,%201)%27]}]}}
Gives me
Update 2
I am trying to construct the URL but I am getting some issues;
<script type="text/javascript">// <![CDATA[
var carbon = {
type: 'bar',
data: {
labels: ['Average Investment', 'Sustainable Investment'],
datasets: [{
label: 'Tonnes of CO2 per year',
data: [11, 5],
borderWidth: 1,
backgroundColor: ['rgba(234, 82, 4, 0.2)', 'rgba(0, 121, 109, 0.2)'],
borderColor: ['rgba(234, 82, 4, 1)', 'rgba(0, 121, 109, 1)'],
}]
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
color: '#fff',
backgroundColor: 'rgba(34, 139, 34, 0.6)',
borderColor: 'rgba(34, 139, 34, 1.0)',
borderWidth: 1,
borderRadius: 5,
formatter: (value) => {
return value + 'k';
},
},
},
legend: {
labels: {
fontColor: 'white'
}
},
title: {
display: true,
text: 'Tones of CO2 pear year'
},
scales: {
xAxes: [{
ticks: {
fontColor: 'white'
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
fontColor: 'white'
},
gridLines: {
color: 'rgba(255, 255, 255, 0.1)'
},
}]
}
}
};
var link = JSON.stringify(carbon);
var link0 = JSON.parse(link);
var link2 = encodeURI(link0);
console.log(typeof link0+ " "+typeof link+" ------------------ "+typeof link2);
// ]]></script>
<div><img width="200" height="100" src="https://quickchart.io/chart?c="/></div>
Which should render the following
Which version of Chart.js are you using because it seems to be working fine with your config.
quickChart: https://quickchart.io/chart?bkg=%23002A5E&c={%20type:%20%27bar%27,%20data:%20{%20labels:%20[%27Investment%27,%20%27Sustainable%27],%20datasets:%20[%20{%20label:%20%27Tonnes%20of%20CO2%20per%20year%27,%20data:%20[11,%205],%20borderWidth:%201,%20backgroundColor:%20[%20%27rgba(234,%2082,%204,%200.2)%27,%20%27rgba(0,%20121,%20109,%200.2)%27%20],%20borderColor:%20[%20%27rgba(234,%2082,%204,%201)%27,%20%27rgba(0,%20121,%20109,%201)%27%20],%20}%20]%20},%20options:%20{%20legend:%20{labels:%20{fontColor:%20%27white%27}},%20scales:%20{%20xAxes:%20[{ticks:%20{fontColor:%20%27white%27}}],%20yAxes:%20[{%20ticks:%20{%20beginAtZero:%20true,%20fontColor:%20%27white%27%20},%20gridLines:%20{%20color:%20%27rgba(255,%20255,%20255,%200.1)%27%20},%20}]%20}%20}%20}
var options = {
type: 'bar',
data: {
labels: ['Investment', 'Sustainable'],
datasets: [{
label: 'Tonnes of CO2 per year',
data: [11, 5],
borderWidth: 1,
backgroundColor: [
'rgba(234, 82, 4, 0.2)',
'rgba(0, 121, 109, 0.2)'
],
borderColor: [
'rgba(234, 82, 4, 1)',
'rgba(0, 121, 109, 1)'
],
}]
},
options: {
legend: {
labels: {
fontColor: 'white'
}
},
scales: {
xAxes: [{
ticks: {
fontColor: 'white'
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
fontColor: 'white'
},
gridLines: {
color: 'rgba(255, 255, 255, 0.1)'
},
}]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
canvas {
background-color: #002A5E;
}
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>
I'm trying to visualize the following dataset with chart.js
var data =
{
"count": 2,
"result": {
"2020-01-22": {
"confirmed": 12,
"deaths": 5,
"recovered": 4
},
"2020-01-23": {
"confirmed": 20,
"deaths": 3,
"recovered": 2
}
}
}
So far I've figured out how to use the dates as label.
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
data: { // mapping the dates as labels
labels: Object.entries(data.result).map( (item) => item[0]),
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: ??
},{
label: 'My Second dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: ??
},{
label: 'My Third dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: ??
}]
}, // Configuration options go here
options: {}
});
I'd like to display the values of 'confirmed', 'deaths' and 'recovered' as three lines within this chart. Therefore I would include three different datasets right? How would I access the required information from json as array to populate the data arrays?
Thanks for your support
just map the key and values to appropriate arrays and consume them as datasets and labels.
var data = {
"count": 2,
"result": {
"2020-01-22": {
"confirmed": 12,
"deaths": 5,
"recovered": 4
},
"2020-01-23": {
"confirmed": 20,
"deaths": 3,
"recovered": 2
}
}
}
var dates = Object.keys(data["result"]).map(x => x);
var confirm = Object.values(data.result).map(x => x.confirmed);
var deaths = Object.values(data.result).map(x => x.deaths);
var recovered = Object.values(data.result).map(x => x.recovered);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: dates,
datasets: [{
label: 'confirmed',
data: confirm,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
},
{
label: 'Deaths',
data: deaths,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}, {
label: 'recovered',
data: recovered,
backgroundColor: 'rgba(255, 206, 86, 0.2)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="100" height="50"></canvas>