Chart.js coming up as blank - chart.js

I'm using chart.js in a plain JavaScript page and the chart is coming up as blank. I am not getting any errors in the Google Chrome console. Below is the code I am using
<!DOCTYPE html>
<html lang="en">
<head th:replace="fragments/header :: head('Home')"></head>
<body>
<header th:replace="fragments/header :: header"> </header>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="container">
<div>
<canvas id="myChart" width="200" height="200"></canvas>
</div>
</div>
<script>
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const chartData = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'line',
chartData,
options: {}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
<!-- Bootstrap core JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
</body>
Can chart.js be using with plain JavaScript? Is there anything wrong with the code I am using?

Please assign data key in config to assign chartdata
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const chartData = {
labels: labels,
datasets: [{
label: 'My First dataset',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'line',
data: chartData,
options: {}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="container">
<div>
<canvas id="myChart" width="200" height="200"></canvas>
</div>
</div>

Related

Chart.js customize individual vertical axis labels

I am using Chart.js to create a horizontal bar chart as shown below. The y axis has three labels: A, B, C. How do I style those vertical labels individually? For example, I may want to have one or two of those labels bolded and/or red.
I looked at this answer: https://stackoverflow.com/a/65463614/3851085. However, that is a solution for the x-axis. For the y-axis, there needs to be a different solution to compute the x pixel of each label.
The code snippet is with an older version of Chart.js, but I am actually using the latest version.
<html>
<head>
<title>Horizontal Bars</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</head>
<body>
<div>
<canvas id="canvas" height="100"></canvas>
</div>
<script>
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [[1, 3], [4, 5], [2, 6]],
backgroundColor: 'lightblue'
}]
},
options: {
responsive: true,
legend: {
display: false,
}
}
});
};
</script>
</body>
</html>
The documentation is unclear about that, but you can use arrays in options to configure labels.
Here is your code, refactored to be compatible with Chart.js 4.2.0:
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [[1, 3], [4, 5], [2, 6]],
backgroundColor: 'lightblue'
}]
},
options: {
responsive: true,
indexAxis: 'y',
scales: {
y: {
ticks: {
color: ['#ff0000', '#000000', '#000000'],
font: {
weight: ['bold', 'bold', 'normal']
}
}
}
},
plugins: {
legend: {
display: false
}
}
}
});
};
.chart-container {
position: relative;
height: 90vh;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#4.2.0"></script>
<div class="chart-container">
<canvas id="myChart"></canvas>
</div>

Layered box annotations

Is it possible to draw a box annotation on top of another one?
I need to have two bands, one higher than the other as shown below.
I was able to achieve so by using three annotations with the code below. But, it would be better if I can just have two annotations (one with yMin: 4, yMax: 14 and another with yMin: 2, yMax: 18)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js#4.1.1/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation#2.1.1/dist/chartjs-plugin-annotation.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script>
const ctx = document.getElementById('myChart');
const inner = {
type: 'box',
borderWidth: 0,
drawTime: 'beforeDraw',
yMin: 4,
yMax: 14,
backgroundColor: '#bdc3c7'
};
const outerUpper = {
type: 'box',
borderWidth: 0,
drawTime: 'beforeDraw',
yMin: 2,
yMax: 4,
backgroundColor: '#ecf0f1'
};
const outerLower = {
type: 'box',
borderWidth: 0,
drawTime: 'beforeDraw',
yMin: 14,
yMax: 18,
backgroundColor: '#ecf0f1'
};
new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [12, 19, 3, 5, 2, 3],
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins: {
legend: {
display: false
},
annotation: {
annotations: {
inner,
outerUpper,
outerLower
}
}
}
},
});
</script>
</body>
</html>

ChatJS 2.8 chaning x-Axis font style and color

I have a ChartJS 2.8 code below. I want to change the font-family (style) of the x-Axis by applying a custom font and also changing x-Axis labels to red color. I tried as below and it is not working. Any help please?
Note: Please keep the library 2.8.0, do not change it.
Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="favicon.ico">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.0.0/polyfill.min.js"></script>
<link href="https://fonts.cdnfonts.com/css/benchnine" rel="stylesheet">
<style>
#import url('https://fonts.cdnfonts.com/css/benchnine');
</style>
</head>
<body>
<h1 style='font-family:"BenchNine";'>BenchNine 222 444</h1>
<div class="reportGraph" style="width:860px;margin:auto;">
<canvas id="chartJSContainer" height="250"></canvas>
</div>
<script>
var options = {
type: "bar",
data: {
datasets: [
{
label: "20. June. 2021 01:08",
data: [98,92,94,98,100,96,28,-18,96,70],
borderColor: "black",
backgroundColor: "transparent",
type: "line",
borderWidth: 1,
lineTension: 0,
fill: false
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
min: -100,
max: 100
}
}],
xAxes: [{
labels: ["111", "222", "333", "444", "555", "666", "777", "888", "999", "000"],
scaleLabel: {
fontFamily: "BenchNine",
fontColor: "red"
}
}
]
},
responsive: true
}
};
var chart = new Chart(document.getElementById("chartJSContainer"), options);
</script>
</body>
</html>
Instead of specifying the fontFamily and fontColor for the scaleLabel which is the scale title you need to specify it in the ticks part, to achieve this just change scaleLabel to ticks
Live example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="favicon.ico">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.0.0/polyfill.min.js"></script>
<link href="https://fonts.cdnfonts.com/css/benchnine" rel="stylesheet">
<style>
#import url('https://fonts.cdnfonts.com/css/benchnine');
</style>
</head>
<body>
<h1 style='font-family:"BenchNine";'>BenchNine 222 444</h1>
<div class="reportGraph" style="width:860px;margin:auto;">
<canvas id="chartJSContainer" height="250"></canvas>
</div>
<script>
var options = {
type: "bar",
data: {
datasets: [{
label: "20. June. 2021 01:08",
data: [98, 92, 94, 98, 100, 96, 28, -18, 96, 70],
borderColor: "black",
backgroundColor: "transparent",
type: "line",
borderWidth: 1,
lineTension: 0,
fill: false
}]
},
options: {
scales: {
yAxes: [{
ticks: {
min: -100,
max: 100
}
}],
xAxes: [{
labels: ["111", "222", "333", "444", "555", "666", "777", "888", "999", "000"],
ticks: {
fontFamily: "BenchNine",
fontColor: "red"
}
}]
},
responsive: true
}
};
var chart = new Chart(document.getElementById("chartJSContainer"), options);
</script>
</body>
</html>

Is there a way to put an image into the legend of a bar chart (chart.js)?

A simple stacked bar graph
<head>
<title>Stacked Bar Chart</title>
<script src="Chart.bundle.js"></script>
<script src="utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width: 75%">
<canvas id="canvas"></canvas>
</div>
<button id="randomizeData">Randomize Data</button>
<script>
chartColors = {
redborder: 'rgba(206, 0, 23, 1)',
darkredborder: 'rgba(206, 0, 23, 0.75)',
lightredborder: 'rgba(206, 0, 23, 0.5)',
};
var barChartData = {
labels: [1<img src='images/badges/Manchester United.png' alt='Manchester United.png' height='30' width='30'>,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],
datasets: [{
label: 'Goals',
backgroundColor: window.chartColors.redborder,
data: [0,1,3,0,2,0,0,2,0,1,0,1,1,0,0,1,0,0,2,1,0,1,2,1,1,0,0,0,2,2,0,3]
}, {
label: 'Assists',
backgroundColor: window.chartColors.darkredborder,
data: [0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1]
}, {
label: 'Indirect',
backgroundColor: window.chartColors.lightredborder,
data: [0,0,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,1,0,1,2,0,0,0,1,0,0,0,0,1]
}]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};
document.getElementById('randomizeData').addEventListener('click', function() {
barChartData.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
window.myBar.update();
});
</script>
</body>
</html>
in the x-axis labels, I am trying to get a small icon (image) to be displayed instead of a number. I have tried to put just the image tag in all possible combinations of " and ' as well as with the number. But to no avail. The chart does not render. It seems that the label needs to recognized as a value to render and the html tag knocks this out of place. I don't see why an image tag cannot be put in there, is there a way to do this?

Chart.js inside in UpdatePanel using Bootstrap Modal

I am trying to show Bar Chart in Bootstrap Modal Popup. But everything is fine when it is call outside UpdatePanel.
If I call the cart inside UpdatePanel, it is showing nothing. Please help me:
My jQuery:
<script type="text/javascript">
var randomScalingFactor = function () { return Math.round(Math.random() * 100) };
var lineChartData =
{
//labels: ["January", "February", "March", "April", "May", "June", "July"],
labels: <% =this.ChartLabels %>,
datasets:
[
{
label: "Query Count",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
//data: [0, 1, 4, 6, 10, 8, 6]
data: <% =this.ChartData1 %>
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
//data: [28, 48, 40, 19, 86, 27, 90]
data: <% =this.ChartData2 %>
}
]
}
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RunThisAfterEachAsyncPostback);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
DrawChart();
}
}
function DrawChart()
{
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
//Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Bar(lineChartData, {
responsive: true
});
}
$('#modChart').modal('show')
DrawChart();
</script>
I am calling the Jquery from CodeBehind :
protected void Button1_Click(object sender, EventArgs e)
{
public string ChartLabels = null;
public string ChartData1 = null;
public string ChartData2 = null;
this.ChartLabels = "['January', 'February', 'March', 'April', 'May', 'June', 'July']";
this.ChartData1 = "[65, 59, 80, 81, 56, 55, 40]";
this.ChartData2 = "[28, 48, 40, 19, 86, 27, 90]";
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallMyFunction", "DrawChart()", true);
}
My ASPX Button inside in UpdatePanel:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal fade" id="modChart" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="exampleModalLabel">Linechart</h4>
</div>
<div class="modal-body">
<div>
<canvas id="canvas" width="568" height="300"></canvas>
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>