Related
I want the chart to be much larger regardless of the values. Currently, the chart is the height in the picture and it does not change. This is the complete configuration for the chart I currently have. Is it possible for the chart to have more height regardless of the dataset values?
const KYCctx = document.getElementById('kycChart').getContext('2d');
const KYCChart = new Chart(KYCctx, {
type: 'bar',
data: {
labels: ["Approved", "Denied", "Pending"],
datasets: [{
data: [65, 59, 80],
backgroundColor: [
'rgba(203, 55, 55, 0.2)',
' rgba(39, 187, 101, 0.5)',
'rgba(255, 171, 45, 0.1)'
],
borderColor: [
' rgba(203, 55, 55, 1)',
'rgba(34, 195, 107, 1)',
'rgba(255, 171, 45, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
grid: {
color: 'rgb(33,34,37)'
}
}
},
plugins: {
legend: {
position: 'bottom',
labels: {
usePointStyle: true,
pointStyle: 'circle',
boxWidth: 6,
generateLabels: (chart) => {
console.log(chart);
return chart.data.labels.map(
(label, index) => ({
text: label,
fillStyle: chart.data.datasets[0].backgroundColor[index],
strokeStyle: chart.data.datasets[0].backgroundColor[index],
}
)
)
}
}
},
title: {
display: true,
align: "start",
color: "#ffff",
font: {
size: 18,
weight: 700,
lineHeight: 2
},
padding: {
bottom: 20
}
}
}
}
});
You could explicitly define the height on the canvas.
<canvas id="kycChart" height="400"></canvas>
const KYCChart = new Chart('kycChart', {
type: 'bar',
data: {
labels: ["Approved", "Denied", "Pending"],
datasets: [{
data: [65, 59, 80],
backgroundColor: [
'rgba(203, 55, 55, 0.2)',
' rgba(39, 187, 101, 0.5)',
'rgba(255, 171, 45, 0.1)'
],
borderColor: [
' rgba(203, 55, 55, 1)',
'rgba(34, 195, 107, 1)',
'rgba(255, 171, 45, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true,
grid: {
color: 'rgb(33,34,37)'
}
}
},
plugins: {
legend: {
position: 'bottom',
labels: {
usePointStyle: true,
pointStyle: 'circle',
boxWidth: 6,
generateLabels: (chart) => {
return chart.data.labels.map(
(label, index) => ({
text: label,
fillStyle: chart.data.datasets[0].backgroundColor[index],
strokeStyle: chart.data.datasets[0].backgroundColor[index],
})
)
}
}
},
title: {
display: true,
align: "start",
color: "#ffff",
font: {
size: 18,
weight: 700,
lineHeight: 2
},
padding: {
bottom: 20
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="kycChart" height="400"></canvas>
Y have this issue:
User 1 repeats twice in two colors, gray and white.
Gray should not be seen
This problem starts when I put styles to the x axis, it repeats the labels.
is there any solution for this case?
The requirement is simply to change the color of the axis labels and ticks.
The gray bar is at the bottom, that is, it does not stack with the red and blue ones
var data = {
labels: ["User1", "User2"],
datasets: [
{
stack:1,
label: "TotalTime",
backgroundColor: "red",
borderWidth: 1,
data: [50, 50],
yAxisID:1
},
{
stack:1,
label: "TotalTime",
backgroundColor: "blue",
borderWidth: 1,
data: [40, 40],
yAxisID:1
},
{
label: "Leave",
backgroundColor: "rgba(191,191,191, 0.5)",
borderWidth: 1,
data: [100, 100],
yAxisID:1
},
],
};
var options = {
indexAxis: "y",
scales: {
y: {
ticks: {
color: "white",
font: {
size: 12,
},
},
stacked: true,
},
x: {
ticks: {
color: "white",
font: {
size: 12,
},
},
}
}
}
var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
canvas{
background-color:black
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.6.2/dist/chart.min.js"></script>
<canvas id="myChart" width="500" height="300"></canvas>
It is because of your yAxisID, you dont define it but chart.js still makes a new axis for it since it isnt made by you with that id, so if you remove that or make it y which you have defined it doesnt make it again anymore
var data = {
labels: ["User1", "User2"],
datasets: [{
label: "TotalTime",
backgroundColor: "red",
borderWidth: 1,
data: [50, 50],
},
{
label: "TotalTime",
backgroundColor: "blue",
borderWidth: 1,
data: [40, 40],
},
{
label: "Leave",
backgroundColor: "rgba(191,191,191, 0.5)",
borderWidth: 1,
data: [100, 100],
},
],
};
var options = {
indexAxis: "y",
scales: {
y: {
ticks: {
color: "white",
font: {
size: 12,
},
},
stacked: true,
},
x: {
stacked: true,
ticks: {
color: "white",
font: {
size: 12,
},
},
}
}
}
var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
canvas {
background-color: black
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.6.2/dist/chart.min.js"></script>
<canvas id="myChart" width="500" height="300"></canvas>
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>
Is there any way to set line color of specific sections in between two points in chart.js?
I would like to color the section 00-07 gray, 07-15 red, and 15-23 blue.
Here is what I am passing as the data attribute in the options object to initialize the chart:
var chartData = {
labels: [/* a single dimensional array of strings */],
datasets: [
{
label: '',
data: [/* a single dimensional array of totals */],
fill: false,
backgroundColor: '#e7eaeb',
borderColor: red
}
]
};
I think this is where I need to add the graph section points and colors, but I do not know how.
HI Michael Hurley I think you should use:
interpolation:
https://www.chartjs.org/docs/latest/samples/line/interpolation.html
or
Multi-axis: https://www.chartjs.org/docs/latest/samples/line/multi-axis.html
My idea is we have 3 datasets with multi-color,
End of dataset1 is first of dataset2.
Here my Example:
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)' };
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var config = {
type: 'line',
data: {
labels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
datasets: [{
label: 'Cubic interpolation (monotone)',
data: [0, 20, 20, 60, 60, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN],
borderColor: window.chartColors.red,
backgroundColor: 'rgba(0, 0, 0, 0)',
fill: false,
cubicInterpolationMode: 'monotone'
}, {
label: 'Cubic interpolation (default)',
data: [NaN, NaN, NaN, NaN, 60, 120, 140, 180, 120, NaN, NaN, NaN, NaN],
borderColor: window.chartColors.blue,
backgroundColor: 'rgba(0, 0, 0, 0)',
fill: false,
}, {
label: 'Linear interpolation',
data: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 120, 125, 105, 110, 170],
borderColor: window.chartColors.green,
backgroundColor: 'rgba(0, 0, 0, 0)',
fill: false,
lineTension: 0
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart - Cubic interpolation mode'
},
tooltips: {
mode: 'index'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
},
ticks: {
suggestedMin: -10,
suggestedMax: 200,
}
}]
}
}
};
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
Latest versions of ChartJS allow you to customize line segments individually, which can be used to change the color and also the style (dashed etc) of a specific segment.
const config = {
type: 'line',
data: {
labels: Utils.months({count: 7}),
datasets: [{
label: 'My First Dataset',
data: [65, 59, NaN, 48, 56, 57, 40],
borderColor: 'rgb(75, 192, 192)',
segment: {
borderColor: ctx => skipped(ctx, 'rgb(0,0,0,0.2)') || down(ctx, 'rgb(192,75,75)'),
borderDash: ctx => skipped(ctx, [6, 6]),
}
}]
},
options: genericOptions
};
See https://www.chartjs.org/docs/master/samples/line/segments.html for more info.
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterLayout hook to create a linear gradient through CanvasRenderingContext2D.createLinearGradient().
In the following example, the linear gradient is created from the colors defined in data.dataset.colors.
new Chart('myChart', {
type: 'line',
plugins: [{
afterLayout: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var gradientStroke = ctx.createLinearGradient(xAxis.left, 0, xAxis.right, 0);
var dataset = chart.data.datasets[0];
dataset.colors.forEach((c, i) => {
var stop = 1 / (dataset.colors.length - 1) * i;
gradientStroke.addColorStop(stop, dataset.colors[i]);
});
dataset.backgroundColor = gradientStroke;
dataset.borderColor = gradientStroke;
dataset.pointBorderColor = gradientStroke;
dataset.pointBackgroundColor = gradientStroke;
dataset.pointHoverBorderColor = gradientStroke;
dataset.pointHoverBackgroundColor = gradientStroke;
}
}],
data: {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
datasets: [{
label: 'My Dataset',
data: [101, 122, 103, 115, 95, 94, 100, 108, 112, 115, 119, 120, 109, 108, 105, 116, 117, 108, 109, 114],
fill: false,
colors: ['gray', 'gray', 'gray', 'gray','gray', 'gray', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue']
}]
},
options: {
scales: {
yAxes: [{
ticks: {
min: 0
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="70"></canvas>
In V3 you can make use of the segment option in the dataset to style specific line parts:
new Chart('myChart', {
type: 'line',
data: {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
datasets: [{
label: 'My Dataset',
data: [101, 122, 103, 115, 95, 94, 100, 108, 112, 115, 119, 120, 109, 108, 105, 116, 117, 108, 109, 114],
segment: {
borderColor: (ctx) => {
const xVal = ctx.p1.parsed.x;
if (xVal <= 7) {
return 'gray';
} else if (xVal <= 15) {
return 'red'
} else {
return 'blue'
}
},
},
}]
},
options: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
<canvas id="myChart" height="70"></canvas>
I've been wanting to let everyone know a way for react chart.
import React from "react";
import { LineController } from 'chart.js';
import Chart from 'chart.js/auto';
class MultiLineController extends LineController {
draw() {
const ctx = this.chart.ctx;
const meta = this.getMeta();
const points = meta.data || [];
const colors = this.getDataset().colors || [];
const area = this.chart.chartArea;
colors.forEach((color, idx) => {
meta.dataset.options.borderColor = color;
meta.dataset.draw(ctx, area, idx, 2);
});
meta.dataset.draw(ctx, area, colors.length, points.length - colors.length);
}
}
MultiLineController.id = "multicolorLine";
MultiLineController.defaults = LineController.defaults;
Chart.register(MultiLineController);
export default function App() {
React.useEffect(() => {
const ctx = document.getElementById("line-chart").getContext("2d");
window.lineChart = new Chart(ctx, {
type: 'multicolorLine',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
colors: ['red', 'green', 'blue', 'yellow']
}]
},
options: {}
});
return () => window.lineChart.destroy();
}, []);
return (
<div style={{width: '100%', height: 300}}>
<canvas id="line-chart" />
</div>
);
}
Here is screenshot of this chart.
React Chart Component implemented by chart.js
I have created a stacked bar chart and i have to hide first dataset's label and its box in legend which is "Total Line", Is there anyway to hide first or any dataset's label. i have read the documentation there is a filter in options but it didn't work.
Hiding This label
Here is the html and js for chart
var ctx = document.getElementById("girth-measure-chart");
var totalLine = [115, 118, 88, 93, 103, 118, 125]
var total = [112, 115, 85, 90, 100, 115, 122]
var arms = [46, 55, 41, 41, 47, 54, 57]
var neck = [17, 20, 15, 15, 17, 20, 21]
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep"],
datasets: [{
type: 'line',
label: 'Total Line',
data: totalLine,
fill: false,
borderColor: ["#ff7899"],
legend: false,
pointBackgroundColor: "#ff151f",
pointRadius: 8,
pointHoverRadius: 8,
pointHoverBackgroundColor: "#990e14",
pointHoverBorderColor: "#6754d3"
}, {
type: 'bar',
label: 'Neck',
data: neck,
backgroundColor: "#e99449",
hoverBackgroundColor: "#d36d14"
}, {
type: 'bar',
label: 'Arms',
data: arms,
backgroundColor: "#49bae9",
hoverBackgroundColor: "#0789bf"
}, {
type: 'bar',
label: 'Total',
data: total,
backgroundColor: "#6754d3",
hoverBackgroundColor: "#260cbd"
}
]
},
options: {
legend: {
display: true,
labels: {
display: true,
boxWidth: 12,
}
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
barThickness: 25,
ticks: {
display: true,
fontFamily: "Montserrat",
fontColor: "#2c405a",
fontSize: 12
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
display: false,
stepSize: 10,
min: 0,
max: 150,
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<div class="chart-container">
<div class="girth-measure-chart-inner" style="width: 100%;">
<canvas id="girth-measure-chart" height=""></canvas>
</div>
</div>
Use the filter method under options.
options: {
legend: {
labels: {
filter: function(legendItem, chartData) {
// return true or false based on legendItem's datasetIndex (legendItem.datasetIndex)
}
}
}
}
In your case return false for the first index and true for the rest.
var ctx = document.getElementById("girth-measure-chart");
var totalLine = [115, 118, 88, 93, 103, 118, 125]
var total = [112, 115, 85, 90, 100, 115, 122]
var arms = [46, 55, 41, 41, 47, 54, 57]
var neck = [17, 20, 15, 15, 17, 20, 21]
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep"],
datasets: [{
type: 'line',
label: 'Total Line',
data: totalLine,
fill: false,
borderColor: ["#ff7899"],
legend: false,
pointBackgroundColor: "#ff151f",
pointRadius: 8,
pointHoverRadius: 8,
pointHoverBackgroundColor: "#990e14",
pointHoverBorderColor: "#6754d3"
}, {
type: 'bar',
label: 'Neck',
data: neck,
backgroundColor: "#e99449",
hoverBackgroundColor: "#d36d14"
}, {
type: 'bar',
label: 'Arms',
data: arms,
backgroundColor: "#49bae9",
hoverBackgroundColor: "#0789bf"
}, {
type: 'bar',
label: 'Total',
data: total,
backgroundColor: "#6754d3",
hoverBackgroundColor: "#260cbd"
}
]
},
options: {
legend: {
labels: {
filter: function(legendItem, chartData) {
if (legendItem.datasetIndex === 0) {
return false;
}
return true;
}
}
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
barThickness: 25,
ticks: {
display: true,
fontFamily: "Montserrat",
fontColor: "#2c405a",
fontSize: 12
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
display: false,
stepSize: 10,
min: 0,
max: 150,
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<div class="chart-container">
<div class="girth-measure-chart-inner" style="width: 100%;">
<canvas id="girth-measure-chart" height=""></canvas>
</div>
</div>