Can't Customize Chart.js - javascript

I'm very new to Chart.js and I'm working off the bar sample included when downloading Chart.js. I read through the documentation and the sample pages seem to do things a little differently. I tried following the documentation and online tutorials to no success, but working off the sample page is yielding better results.
However I can't seem to customize anything. I'm trying to start the scale value at 0 but it won't apply. This happens to all things I try to do (font color etc. etc. etc. etc.) The rest of the options here were included with the file and work. I'm not sure what I'm doing wrong.
<head>
<title>Bar Chart</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../dist/Chart.bundle.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
<script>
var barChartData = {
labels: ["Week 1", "Week 2"],
datasets: [{
label: 'Round 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [12,15]
}, {
label: 'Round 2',
backgroundColor: "rgba(151,187,205,0.5)",
data: [20,17]
}]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
scaleOverride:true,
scaleStartValue: 0,
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
}
}
});
};
</script>
</body>

You can use tick.beginAtZero
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
},
...
Fiddle - http://jsfiddle.net/7mse8p9e/

Related

Send graph values to Chart.js template with Python Flask

I'm trying to make a data visualizer with a Flask and Chart.js api. My application has the following structure:
API
api.py
templates
index.html
static
css
estil.css
js
chartjs.js
(...)
So my idea is to put all the charts in the same file, outside the html. My problem is that I don't know how to send the data that I read from the database with Flask to the chart.js template. Surely it is very easy, but it is the first time that I touch chart.js and javascript and it is resisting me a bit.
(PSEODUCODE)
Python flask api (api.py):
#app.route('/')
def index():
fruits = []
# SQLITE3 QUERY
return render_template("index.html", fruits = fruits)
HTML (index.html):
<canvas id="myChart"></canvas>
<script src="static/js/chartjs.js"
JS (chartjs.js):
const ctx2 = document.getElementById('myChart');
const background_color2 = ['#33a3ec', '#ff6384'];
new Chart(ctx2, {
type: 'doughnut',
data: {
labels: ['Orange', 'Pineaple'],
datasets: [{
data: [82, 38],
/*
* If I put it inside the HTML with <script>TODO</script>
* it works fine for me but if I do it here it doesn't show
* me the graphics:
* data: {% values %},
*/
backgroundColor: background_color2,
borderWidth: 10,
borderColor: "#fbfbfb"
}]
},
options: {
scales: {
display: false
},
animation: {
duration: 1000,
animateRotate: true,
render: false
},
plugins: {
title: {
display: true,
text: "Juice fruits"
},
legend: {
display: true,
position: 'bottom'
}
}
}
});
As always, after not coding for a few hours comes the answer. It occurred to me to create each graph inside a function (like this):
function chartFruitJuice(fruits) {
const ctx = document.getElementById('myChart');
const background_color = ['#33a3ec', '#ffce55', '#4ac1c1', '#ff00ff00'];
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Orange', 'Apple', 'Pineaple'],
datasets: [{
data: fruits,
backgroundColor: background_color,
borderWidth: 10,
borderColor: "#fbfbfb"
}]
}, options: {
scales: {
display: false
},
animation: {
duration: 1000,
animateRotate: true,
render: false
},
plugins: {
datalabels: {
display: true,
align: 'bottom',
backgroundColor: '#ccc',
borderRadius: 3,
font: {
size: 18,
},
},
title: {
display: true,
text: "Fruit juice"
},
legend: {
display: true,
position: 'bottom'
}
}
}
});
}
And in the HTML, pass the Flask values as parameters of said function:
<canvas id="myChart"></canvas>
<script>
charFruitJuice({{ fruits | tojson | safe }});
</script>

Chart.js tooltip not showing on line chart

I'm at a loss as to why my chart's tooltips aren't displaying... can anybody show me what I'm doing wrong?
The tooltips work fine if I set the chart type to "bar" but for some reason don't work with "line". I'm relatively new to chart.js and am probably making some basic newbie mistake?
Here's my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="250" height="150"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels:[],
datasets: [{
label: 'Applicants',
data: [],//start empty
backgroundColor: [
'rgba(10, 168, 196, 0.2)'
],
borderColor: [
'rgba(10, 168, 196, 1)'
],
}]
},
options: {
tooltips: {
enabled: true
},
legend: {
display: false
},
scales: {
xAxes: [{
type: 'time',
// time: {
// unit: 'day'
// }
}],
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
onClick: handleClick
}
});
window.onmessage = function(event){
myChart.data.datasets[0].data = event.data.data;
myChart.data.labels = event.data.labels;
myChart.update();
};
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>
For anyone having problems with this using Chartjs v3, you need to make sure you have registered the Tooltip plugin:
import { Chart, Tooltip } from 'chart.js'
Chart.register([Tooltip])

Chart.js - Font only renders after you reload the canvas

I am using Chart.js and I am trying to use a Google Font. The first time I load the page, the chart uses the default font but if I recreate the chart, then the correct font is loaded.
How do I get the font to load the first time the chart is loaded?
My HTML:
<div style="width: 100%;" id="StatsDiv">
<div id="container" style="position: relative; height:300px; width:600px; background-color:#F9F9F9; padding-top:10px;">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
</div>
The loading of the font:
<link href="https://fonts.googleapis.com/css?family=Asap+Condensed:400,500,600" rel="stylesheet" />
The Javascript that does the work:
Chart.defaults.global.defaultFontFamily = 'Asap Condensed';
var myChart = new Chart(document.getElementById("myChart"), {
type: 'bar',
data: {
labels: [FundsLabel,RequestedLabel],
datasets: [
{
label: "Cleared Balance: " + parseFloat(AVBalance).toFixed(2) + " AUD",
backgroundColor: "rgba(98,203,49,0.40)",
borderColor: "rgba(98,203,49,0.75)",
borderWidth: 2,
hoverBackgroundColor: "rgba(98,203,49,0.50)",
hoverBorderColor: "rgba(98,203,49,1.00)",
data: [AVBalance, GreenRequested],
},
{
label: "Pending Balance: " + parseFloat(PDBalance).toFixed(2) + " AUD",
backgroundColor: "rgba(231,76,60,0.40)",
borderColor: "rgba(231,76,60,0.75)",
borderWidth: 2,
hoverBackgroundColor: "rgba(231,76,60,0.50)",
hoverBorderColor: "rgba(231,76,60,1.00)",
data: [PDBalance, RedRequested],
}
]
},
options: {
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
zeroLineColor: '#999999',
zeroLineWidth: '1',
// color: "rgba(255,99,132,0.2)",
color: "rgba(239, 239, 239)",
},
ticks: {
// min: 0, // it is for ignoring negative step.
beginAtZero: true,
fontSize: "12",
// if i use this it always set it '1', which look very awkward if it have high value e.g. '100'.
}
}],
xAxes: [{
stacked: true,
gridLines: {
display: false,
},
barThickness: 120,
scaleLabel: {
display: true,
//labelString: 'Banks'
}
}]
},
maintainAspectRatio: false,
}
});
wrapping the chart rendering code inside document.fonts.ready.then worked for me
The chart won't load your font on the first time because it couldn't find your font (yet). But it works the second time because your font is already cached by browser.
If you want to make sure the font is working, you can do preload the font by using a hidden DOM.
.fontPreloader{
font-family: 'Asap Condensed';
position: fixed;
top: -9999px;
left: -9999px;
}
<div class="fontPreloader">-</div>
<link href="https://fonts.googleapis.com/css?family=Asap+Condensed:400,500,600" rel="stylesheet" />
Waiting for the window to load before creating the chart worked for me:
window.addEventListener('load', function() {
// An example of creating a chart, replace with your code:
var ctx = document.getElementById("myChart").getContext("2d");
var barchart = new Chart(ctx, config);
})

Chart.js colors in bar chart not showing

I've got a chart.js bar chart that renders fine on desktop but on my iPhone the chart bars are black unless I hover over them and then only the WAY bar changes to the correct color.
Code:
<div class="col-sm">
<canvas id="WayChart" width="300" height="300"></canvas> <!-- max-width="100%" -->
<script>
var densityCanvas = document.getElementById("WayChart");
Chart.defaults.global.defaultFontSize = 18;
Chart.defaults.global.defaultFontColor='black';
var controlData = {
label: 'Control',
data: [5.0,4.2,5.6],
backgroundColor: 'rgba(144,18,179)',
borderWidth: 0,
yAxisID: "WAY Depth"
};
var wayData = {
label: 'WAY',
data: [5.3,2.5,2.6],
backgroundColor: 'rgba(0,166,104)',
borderWidth: 0,
yAxisID: "WAY Depth"
};
var daysData = {
labels: ["Day 0", "Day 28", "Day 56"],
datasets: [controlData, wayData],
};
var chartOptions = {
responsive:true,
scales: {
xAxes: [{
barPercentage: 1,
categoryPercentage: 0.5,
ticks: {
fontStyle:'bold'
}
}],
yAxes: [{
id: "WAY Depth",
scaleLabel:{
display:true,
labelString:'Depth (mm)',
fontStyle:'bold',
},
ticks: {
beginAtZero: true
}
}]
},
title:{
display:'true',
text:'Depth Measurements (mm)',
fontSize:18
}
};
var barChart = new Chart(WayChart, {
type: 'bar',
data: daysData,
options: chartOptions
});
</script>
</div>
</div>
Any ideas?
It renders fine in the Chrome phone inspector window but not on my iPhone using FF and Chrome browsers.
I saw the problem right after posting this.
The backgroundColor was written using rgba and needed to be rgb.
Always the little things...

ChartJS. Change axis line color

I wanna know if it's possible to change the color of the chart axis using ChartJS.
Thanks
I know this question was asked over 2 years ago and the OP has already marked a correct answer, but I have a solution to the problem that the OP mentioned in the comments of the marked answer and I'd like to solve it to save other people some time.
But this changes the color of the axis and all the gridLines, what if
I just want to change the axis color? For example, I want the axis
line solid black and the grid lines grey.
If you're trying to achieve this, then the marked answer won't do it for you but the following should:
yAxes: [{
gridLines: {
zeroLineColor: '#ffcc33'
}
}]
you can change the color by scales configuration under chart options:
type: '...',
data: {...},
options: {
scales: {
xAxes: [{gridLines: { color: "#131c2b" }}],
yAxes: [{gridLines: { color: "#131c2b" }}]
}
}
Good question and good answer from #A Friend
His answer works perfectly well with ....... chart.js v2.xx
Here now for version 3.xx for those interested:
(as v3.xx is not backwards compatible with v2.xx)
Using borderColor instead of zeroLineColor to change the color of the chart axis using Chart.js v3.xx:
scales: {
x: { // <-- axis is not array anymore, unlike before in v2.x: '[{'
grid: {
color: 'rgba(255,0,0,0.1)',
borderColor: 'red' // <-- this line is answer to initial question
}
},
y: { // <-- axis is not array anymore, unlike before in v2.x: '[{'
grid: {
color: 'rgba(0,255,0,0.1)',
borderColor: 'green' // <-- this line is answer to initial question
}
}
}
Following a working snippet with complete code:
const labels=["2021-08-01","2021-08-02","2021-08-03","2021-08-04","2021-08-05"];
const data_1=[39,41,42,43,43];
const data_2=[37,38,40,41,39];
const ctx=document.querySelector('canvas').getContext('2d');
const data = {
labels: labels,
datasets: [{
label: 'Data 1',
borderColor: 'grey',
data: data_1
}, {
label: 'Data 2',
borderColor: 'grey',
data: data_2
}]
};
const options = {
scales: {
x: {
grid: {
color: 'rgba(255,0,0,0.1)',
borderColor: 'red'
}
},
y: {
grid: {
color: 'rgba(0,255,0,0.1)',
borderColor: 'green'
}
}
}
};
const chart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- gets you the latest version of Chart.js, now at v3.5.0 -->
<canvas width="320" height="240"></canvas>
In the Charjs.JS to style the scale label and ticks we can use below settings.
options: {
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'X axe name',
fontColor:'#000000',
fontSize:10
},
ticks: {
fontColor: "black",
fontSize: 14
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Y axe name',
fontColor: '#000000',
fontSize:10
},
ticks: {
fontColor: "black",
fontSize: 14
}
}]
}
}
Please refer the link for all the properties. Study all the property before implementation.
Happy coding !
For ChartJs 3 updated in 2022
You can pass the options object when initializing the context. In the sample code I was use x to change the line color on X Axis, you can try y as well.
options: {
scales: {
x: {
grid: {
color: '#777777'
}
}
},

Categories

Resources