How to pass variables from flask to external javascript in chart js - javascript

I have this chart (as shown below)
let ctx1 = document.getElementById("myChart").getContext('2d');
let labels = ['Banking', 'Finances', 'Shopping', 'Recreation', 'Healthcare', 'Transportation', 'Food and Drink'];
let colorHex = ['#FB3640', '#86A9C5', '#286CA1', '#77FAC', '#1C203D', '#798E9C', '#2A303D'];
let myChart = new Chart(ctx1, {
type: 'pie',
data: {
datasets: [{
data: [10, 10, 10, 10, 10, 10, 10],
backgroundColor: colorHex,
borderWidth: [0,0,0,0,0,0,0]
}],
labels: labels,
},
options: {
responsive: false,
legend: {
position: 'bottom',
labels: {
fontColor: 'white'
}
},
plugins: {
datalabels: {
color: '#fff',
anchor: 'end',
align: 'start',
offset: 10,
borderWidth: 0,
// borderColor: '#fff',
borderRadius: 0,
font: {
size: '10',
color: '#fff'
},
formatter: (value) => {
return value + ' %';
}
}
}
}
})
I call it through the html (as shown below)
<canvas id= "myChart" height="330%" width="330%"></canvas>
What I want to do pass variables in the data attribute in the JS - from my backend in flask so that the values that the chart displays will change.
How do I do this?
Thanks

If you are not using javascript externally then you can pass Flask's variable to Template
view and then in view html you can use directly into the javascript as below:
data: {
datasets: [{
data: {{ chartData | tojson }}, //chartData variable is passed From flask to view template
backgroundColor: colorHex,
borderWidth: [0,0,0,0,0,0,0]
}],
labels: labels,
},
Here chartData is Varible passed from Flask to View html, it will have values like
chartData = [10, 12, 11, 12, 10, 12, 11]

Related

Chart js Horizontal Bar Chart Create legend for every single bar and show/hide bars

I am using charts js version 2.9.4. I am creating a horizontal single-bar chart.
I want to add functionality on legends to Show and hide the single Bar on clicking every legend.
Is it possible to achieve this functionality through chart js or any other chart library?
Thanks!
barChartOptions = {
legend: {
display: true,
position: "bottom",
onHover: function (event, legendItem) {
document.getElementById("mybarChart").style.cursor = "pointer";
},
labels: {
usePointStyle: true,
generateLabels: function (chart) {
var labels = chart.data.labels;
var dataset = chart.data.datasets[0];
var legend = labels.map(function (label, index) {
return {
datasetIndex: 0,
text: label,
fillStyle: dataset.backgroundColor[index],
strokeStyle: dataset.borderColor[index],
lineWidth: 1,
};
});
return legend;
},
},
},
};
yourData = {
labels: [18, 82, 22, 80, 85, 88, 90],
datasets: [
{
data: [1, 2, 3, 4, 10, 12, 15],
barThickness: 20,
backgroundColor: [
"#ff6384",
"#36a2eb",
"#ffce56",
"#4bc0c0",
"#9966ff",
"#9966fe",
"#9955cd",
"#9966ee",
],
borderColor: ["#ff6384", "#36a2eb", "#ffce56", "#4bc0c0", "#9966ff"],
},
],
};
this.chart = new Chart(ctx, {
type: "horizontalBar",
data: yourData,
options: barChartOptions,
});
Thanks

Hover text of canvas in other div

I want to put text beside the canvas doughnut. This text is based on the hover information of each slide, but instead of appear on the top pf the image i want it to be next to it. (2 images as example)
https://jsfiddle.net/jak2e4zr/
HTML
<canvas id="myChart" ></canvas>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
JS
var ctx = document.getElementById("myChart");
var data = {
labels: ['Residential', 'Non-Residential', 'Utility'],
datasets: [
{
data: [19, 26, 55],
weight: 2,
spacing : 5,
borderWidth : 0,
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
circumference: 180,
rotation: -180,
plugins: {
legend: {
display: false
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: 'rgba(0, 0, 0, 0)',
displayColors: false,
titleAlign: 'center',
xAling: 'center'
}
},
hoverOffset: 15,
}
}); `
Image 1
Image 2
THANKS
The chart.js tooltip object accepts an additional property called position which, well, affects the position of the tooltip. By default it only accepts two strings for setting the mode being either "average" or "nearest". Luckily you're able to define your own mode by extending the Chart.Tooltip.positioners object.
As you want your tooltip to be somewhere in the middle, we can make something like this:
Chart.Tooltip.positioners.middle = function(elements, eventPosition) {
const chart = this._chart;
return {
x: chart.chartArea.width/2,
y: chart.chartArea.height/2
};
}
...so simply querying the chart's current dimensions and take the half of it. This mode can then be used by it's name "middle".
Here's a complete example:
var ctx = document.getElementById("myChart");
Chart.Tooltip.positioners.middle = function(elements, eventPosition) {
const chart = this._chart;
return {
x: chart.chartArea.width / 2,
y: chart.chartArea.height / 2
};
}
var data = {
labels: ['Residential', 'Non-Residential', 'Utility'],
datasets: [{
data: [19, 26, 55],
weight: 2,
spacing: 5,
borderWidth: 0,
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
responsive: false,
circumference: 180,
rotation: -180,
plugins: {
legend: {
display: false
},
tooltip: {
position: 'middle',
backgroundColor: '#ff0000',
titleColor: '#000000',
displayColors: false,
titleAlign: 'center',
xAlign: 'left'
}
},
hoverOffset: 15,
}
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

How to reach to a chartjs chart's value?

I have a chartjs line chart that has multiple lines like that;
I have been trying to add a date-time selector but I am not able to update my chart because I don't get how to reach the datas of my chart. Here is my chart decleration;
var ctx = document.getElementById('canvas');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: time1, time2,
datasets: [
{
label: 'Temperature - 1',
data: temp1,
backgroundColor: 'transparent',
borderColor: 'red',
borderWidth: 3
},
{
label: 'Temperature - 2',
data: temp2,
backgroundColor: 'transparent',
borderColor: 'purple',
borderWidth: 3
},
{
label: 'Humidity - 1',
data: hum1,
backgroundColor: 'transparent',
borderColor: 'green',
borderWidth: 3
},
{
label: 'Humidity - 2',
data: hum2,
backgroundColor: 'transparent',
borderColor: 'yellow',
borderWidth: 3
}]
},
options: {
elements: {
line: {
tension: 0
}
},
scales: {
y: {
title: "Temperature/Humidity",
beginAtZero: true,
min: 10,
max: 60
}
}
}
});
time1, time2, temp1, temp2, hum1, hum2 are all array. When I want to update the chart using chart.update() function that I read at its own documentation, as I said I don't get it how to reach to data arrays like temp1, temp2.
Something like myChart.data.datasets.data would not work, making them like json;
{first_data:{
label: 'Temperature - 1',
data: temp1,
backgroundColor: 'transparent',
borderColor: 'red',
borderWidth: 3
}},
Doesn't work also, how can I reach to temp1 for example?
SOLUTION:
Because of my carelessness I had asked a nonsense question. Because of myChart.data.datasets is an object, I am able to reach to temp1 like myChart.data.datasets[0].data, sorry everyone
You will need to target the specific dataset you want to get the data from so to get the data of the Temperature - 1 dataset you will need to target it like this: myChart.data.datasets[0].data
Example:
var 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: {}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const myChart = new Chart(ctx, options);
console.log(myChart.data.datasets[0].label)
console.log(myChart.data.datasets[0].data)
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

problem with chart js pie chart dataset data

This is the output of the code which I don't want since each data sits inside the other, I followed the documentation and other code examples but to no avail.
here is my code
let labelCharts: string[] = ['Supplier Debt', 'Raw Material Cost', 'Product Cost', 'Customer Debt'];
let myDoughnutChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: labelCharts,
datasets: [{
backgroundColor: "#3e95cd",
borderWidth: 10,
label: 'Supplier Debt',
data: [1, 5, 1],
},
{
data: rawMatCostArr,
backgroundColor: "#8e5ea2",
borderWidth: 10,
label: 'Raw Material Cost',
},
{
data: productCostArr,
backgroundColor: "#3cba9f",
borderWidth: 10,
label: 'Product Cost',
},
{
data: agentsDebtArr,
backgroundColor: "#e8c3b9",
borderWidth: 10,
label: 'Customer Debt',
}
]
},
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Total'
}
}
});
note that each variable inside the data property is an array
To achieve the behaviour you want you only need 1 dataset and put the sum of the data in it. If you use it like shown in this config you get the desired outcome:
const config = {
type: 'pie',
data: {
labels: ['Supplier Debt', 'Raw Material Cost', 'Product Cost', 'Customer Debt'],
datasets: [{
backgroundColor: ["#3e95cd","#8e5ea2","#3cba9f","#e8c3b9"],
borderWidth: 10,
label: 'Supplier Debt',
data: [1, 5, 3,6],
}
]
},
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Total'
}
}
};
You might want to decrease the border with since it will make your chart look a lot better.

Chart.js: Fill background between two lines

I have line chart with two lines. First line is static, second line builds dynamically. I need to fill area between first and second line if y value of second line above a y value of first line.
I used Charts.js library for chart building
Currently I have next result (Fill between two lines):
Expected result:
Very hackish way but it gives the expected result :D!
Fiddle -> http://jsfiddle.net/Lzo5g01n/28/
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Yellow", "Blue", "Green", "Orange", "Pink"],
datasets: [{
fill: false,
data: [0, 10, , 10, 0],
backgroundColor: 'black',
borderColor: 'black',
borderWidth: 1
}, {
data: [10, 10, 10, 10, 10],
fill: true,
backgroundColor: 'white',
borderColor: 'black',
borderWidth: 1
}, {
data: [, 10, 18, 10, ],
backgroundColor: 'black',
borderColor: 'black',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
display: false,
ticks: {
beginAtZero: true
}
}],
xAxes: [{
display: false
}]
},
legend: {
display: false
},
tooltips: {
enabled: false
},
elements: {
point: {
radius: 0
}
}
}
});

Categories

Resources