Dynamic Chart on Popover Error - Cannot Acquire Context - javascript

I am trying to create a chart js popover but I am getting the error:
Failed to create chart: can't acquire context from the given item
I think that this is probably happening because the canvas tag is created dynamically, but I am not sure how to fix it. Any ideas? This is the js code I am using:
$(function() {
$('[data-toggle="popover"]').popover({
html: true,
content: '<canvas id="myChart" width="400" height="400"></canvas>',
}).on('shown.bs.popover', function() {
new Chart($('#myChart'), {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
},
// Configuration options go here
options: {}
});
});
HTML:
<button type="button" class="btn btn-lg btn-primary" data-toggle="popover" title="Good vs. Evil Winrate" data-placement="bottom">Who's Winning?</button>

Related

How to add on click event to chart js

Hello I have a question concerning js charts. I have already created one in django application and i want to generate a javascript alert by clicking a certain point in the chart.
How can the alert get the value of the point that i choose?
For example with the value 92 like what is shown in the figure below:
This can be done with an onClick even handler as follows:
onClick: (event, elements, chart) => {
if (elements[0]) {
const i = elements[0].index;
alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]);
}
}
Please take a look at below runnable code and see how it works.
new Chart('myChart', {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: '# of Votes',
data: [65, 59, 80, 81, 56, 55, 40],
borderColor: '#a00'
}]
},
options: {
onClick: (event, elements, chart) => {
if (elements[0]) {
const i = elements[0].index;
alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]);
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" width="400" height="95"></canvas>

make horizontal graph with percentage :react js

I trying to make a horizontal chart with react-chartjs i want each data to show the percentage
import React, { Component } from "react";
import { HorizontalBar } from "react-chartjs-2";
export default class Button extends Component {
render() {
const dataHorBar = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
return (
<div>
<HorizontalBar data={dataHorBar} />
</div>
);
}
}
Here is the code of what I have tried
https://codesandbox.io/s/react-chartjs-bar-horizontal-bar-forked-be9wil
I also want to remove the background lines and make the graph more rounded edge
In order to use the feature for having rounded rectangles, you need to update to the v3 of chartjs, therefore, the following code will be working only on this version. But you can adapt it to a previous version, you will just not be able to change the border radius of the rectangle.
You can use the datalabels plugin, in order to display custom text in your chart, and format the label like this:
options: {
plugins: {
datalabels: {
formatter: value => value + " %", // Add the percentage after the value
align: "end",
anchor: "end",
clip: true,
}
}
}
For the shapes, you can use the option borderRadius, to have rounded edges. You can find more information here, but in the end, you just have to specify a value for the borderRadius, in each dataset:
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40],
borderRadius: 50, // Give a number
}
]
Finally, for removing the grid lines, you can use this snippet, and pass those options to your chart
options: {
scales: {
x: {
grid: {
display: false // Hide x grid
}
},
y: {
grid: {
display: false // Hide y grid
}
}
}
};
That's it for the ground principle. Here is a live working example, if you really wants to see how to implement it.

How can I configure Chart.js in a Electron app?

I'm new to electron so I'm learning the basic configuration.
So, i want to implement chart.js in my electron app.
The problem is: on my main page, the chart is simply a blank space... but with a look in the html inspector I can see the canvas created.
What I already did:
I've installed chart.js with npm install chart.js --save which we can find in the official chart.js documentation (https://www.chartjs.org/docs/latest/getting-started/installation.html).
My feeling tells me that I'm doing something wrong in the call for the chart library or something like that. My code is below:
<canvas id="myChart"></canvas>
<script>
const { chart } = require('electron-chartjs');
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
</script>
As you can see, I'm using the official example. The only addition was the const { chart } = require('electron-chartjs');. So, I believe I'm doing something wrong or ignoring some big step.
Update:
Here is the new code:
<canvas id="chart"></canvas>
<script>
var Chart = require('chart.js');
var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
</script>
I had to require "chart.js", but i was requiring "electron-chart,js". And the canvas id was wrong.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
// ** entire Chart.js library **
</script>
<style>
</style>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
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: {{chartData}}
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
</script>
</body>
</html>
Notice the placeholder {{chartData}}. Also do note that you have to substitute in the actual script from the Chart.js file (you could link to the script file, but then you'll need a module that serves up static files)
var http = require('http');
var fs = require('fs');
http.createServer(function (req, response) {
fs.readFile('index.html', 'utf-8', function (err, data) {
response.writeHead(200, { 'Content-Type': 'text/html' });
var chartData = [];
for (var i = 0; i < 7; i++)
chartData.push(Math.random() * 50);
var result = data.replace('{{chartData}}', JSON.stringify(chartData));
response.write(result);
response.end();
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
We just substitute the placeholder with actual data.
Update for electron 21.2.0.
Download chart.js module from npm
Modify Index.html:
Add 'unsafe-inline' in meta
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'">
Now we can use chart.js as usual.
I only have no idea how to set custom width/height of my chart ):
Demo code is available on:
https://github.com/zdzmzych/electronNoiseAnalyzer

Chart JS Line Graph multitooltipkey background color issue

I have a question about Chart.js. I am using a line graph with 2 sets of data (2 lines) and when i hover over the data it shows the "legend". In the legend are 2 boxes that can be colored. I can change the background color of the boxes with no issue but when I change the color it applies to both boxes. How can I set the color of the box separately? Thanks.
<canvas
class="ex-line-graph"
width="1200" height="1200"
data-chart="line"
data-scale-start-value="0"
data-scale-step-width ="100"
data-scale-steps ="4"
data-point-fill-color = "RGBA( 255,28,221,.3)"
data-scale-line-color="transparent"
data-scale-grid-line-color="rgba(255,255,255,.05)"
data-scale-font-color="#a2a2a2"
data-labels=" ['April','May','June','July','August','September','October','November','December ','January','February','March']"
data-value="[{ fillColor: 'RGBA( 28,168,221,.3)', strokeColor:
'#1CA8DD', label:'Data', data: [151, 154, 173, 169, 176,161,0,0,0,0,0,0]}, {fillColor: 'RGBA(37,40,48,.0)', strokeColor: 'rgba(255,255,255,1)', label :'Target', data: [200, 200,200,200,200, 200,200,200,200, 200,200,200] }]">
</canvas>
It's a 2 part answer if I follow correctly:
1.- Specify colors on your data set:
var data = {
labels: ["January", "February", "March", "April", "May"],
datasets: [{
label: "Series A",
data: [10, 30, 20, 40, 10],
borderColor: "rgba(0,0,255,0.8)",
backgroundColor:"rgba(0,0,255,0.5)"
}, {
label: "Series B",
data: [25, 40, 10, 40, 30],
borderColor: "rgba(255,0,0,0.8)",
backgroundColor:"rgba(255,0,0,0.5)"
}]
};
And enable the tooltips on the options Object (Notice the mode Label):
var options = {
tooltips: {
enabled: true,
mode: 'label'
},
legend: {
display: true,
}
};
Result:
Codepen:
Codepen - Chart.js Multiline Tooltip labels

How can I change the font (family) for the labels in Chart.JS?

I want to change the font to something snazzier in my Chart.JS horizontal bar chart. I've tried the following, but none of it works:
var optionsBar = {
. . .
//fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara'"
label: {
font: {
family: "Georgia"
}
}
};
I also read that this would work:
Chart.defaults.global.defaultFont = "Georgia"
...but where would this code go, and how exactly should it look? I tried this:
priceBarChart.defaults.global.defaultFont = "Georgia";
...but also to no good effet.
For the full picture/context, here is all the code that makes up this chart:
HTML
<div class="chart">
<canvas id="top10ItemsChart" class="pie"></canvas>
<div id="pie_legend"></div>
</div>
JQUERY
var ctxBarChart =
$("#priceComplianceBarChart").get(0).getContext("2d");
var barChartData = {
labels: ["Bix Produce", "Capitol City", "Charlies Portland",
"Costa Fruit and Produce", "Get Fresh Sales",
"Loffredo East", "Loffredo West", "Paragon", "Piazza Produce"],
datasets: [
{
label: "Price Compliant",
backgroundColor: "rgba(34,139,34,0.5)",
hoverBackgroundColor: "rgba(34,139,34,1)",
data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027,
25553]
},
{
label: "Non-Compliant",
backgroundColor: "rgba(255, 0, 0, 0.5)",
hoverBackgroundColor: "rgba(255, 0, 0, 1)",
data: [170, 10, 180, 140, 30, 10, 50, 100, 10]
}
]
}
var optionsBar = {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
},
//fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara'"
//Chart.defaults.global.defaultFont = where does this go?
label: {
font: {
family: "Georgia"
}
}
};
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar
});
//priceBarChart.defaults.global.defaultFont = "Georgia";
I even tried this:
CSS
.candaraFont13 {
font-family:"Candara, Georgia, serif";
font-size: 13px;
}
HTML
<div class="graph_container candaraFont13">
<canvas id="priceComplianceBarChart"></canvas>
</div>
...but I reckon the canvas drawing takes care of the font appearance, as adding this made no difference.
UPDATE
I tried this and it completely broke it:
Chart.defaults.global = {
defaultFontFamily: "Georgia"
}
UPDATE 2
As Matthew intimated, this worked (before any of the chart-specific script):
Chart.defaults.global.defaultFontFamily = "Georgia";
This should be useful: http://www.chartjs.org/docs/. It says "There are 4 special global settings that can change all of the fonts on the chart. These options are in Chart.defaults.global".
You'll need to change defaultFontFamily for the font. And defaultFontColor, defaultFontSize, and defaultFontStyle for color, size, etc.
If you wanted to add the font-family to the chart object then you can add it in the options object.
options: {
legend: {
labels: {
fontFamily: 'YourFont'
}
}...}
Here is a link to the docs: https://www.chartjs.org/docs/latest/general/fonts.html
Change font size, color, family and weight using chart.js
scales: {
yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
}
See the full code
<!doctype html>
<html>
<head>
<title>Chart.js</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<script src="js/Chart.bundle.js"></script>
<script src="js/utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
font-weight:700;
}
</style>
</head>
<body>
<div id="container" style="width:70%;">
<canvas id="canvas"></canvas>
</div>
<script>
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var color = Chart.helpers.color;
var barChartData = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: [{
label: 'Completed',
// Green
backgroundColor: '#4caf50',
borderColor: '#4caf50',
borderWidth: 1,
data: [
5, 15, 25, 35, 45, 55
]
}, {
label: 'Created',
// Blue
backgroundColor: '#1976d2',
borderColor: '#1976d2',
borderWidth: 1,
data: [
10, 20, 30, 40, 50, 60
]
}]
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
onClick: null
},
title: {
display: true,
text: '',
fontSize: 20
},
scales: {
yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
}
}
});
};
</script>
</body>
</html>
You named the chart priceBarChart in the following part of your code:
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar
})
Which means that priceBarChart.defaults.global.defaultFont = 'Georgia' will 'dive' into the variable priceBarChart, go into its default properties, change one of its global properties and that one is defaultFont, exactly what you want.
But when you apply this code, you basically create the chart with the wrong font and then change it again, which is a bit ugly. What you need to do is tell the chart what the font is beforehand.
You do this by merging your font declaration with the rest of the options, just like how you did it with your variables barChartData and optionsBar.
After you've created barChartData and optionsBar, create another variable with the name, let's say, defaultOptions, like so:
var defaultOptions = {
global: {
defaultFont: 'Georgia'
}
}
You can see that it has the same structure. You go into the global options, and change its defaultFont property. Now you need to apply it to the created chart at the moment it is created, like so:
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar,
defaults: defaultOptions //This part has been added
})
This method of overwriting options is what is being used in almost every JavaScript plugin. When you create a new instance, the plugin copies an object that contains objects that contain objects and so forth. But these objects can be modified with additional options, like barChartData, optionsBar and defaultOptions.
I hope this helps!

Categories