How to extract ChartJs data and config properties - chart.js

We're trying to give colleagues the ability to share ChartJS graphs with each other. Most of our current graphs are dynamic and users can apply filters (dates, add/remove data etc).
The plan is to have a button that, on click, will get the data and properties (labels, line colours, borderWidth, chart type etc) and pass this data via a url. The user can then send that link to someone else. They can open it up to view that chart captured as it was seen by the original user, like a screenshot, but with all the interactive features enabled.
E.g.
stackoverflow.com/shared_chart.php?conf=%7B%22responsive%22:true,%22responsiveA
When a chart is created by myChart = new Chart(ctx, config); ChartJs adds a lot of new properties to the chart object (e.g $plugin, _meta) that I don't need.
And, when I JSON.stringify(myChart.config) I get an error "Uncaught TypeError: Converting circular structure to JSON".
I've added the code needed to create a sample bar chart below:
// HTML needs a canvas element
<-- <canvas id="myChart"></canvas> -->
const ctx = $('#myChart');
let config;
let myChart;
// config would look something like this
config = {
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: 'rgba(92,184,92,0.5)',
borderColor: 'rgba(92,184,92,1.000)',
borderWidth: 2,
data: [
1,2,3,4,3,2,1
]
}, {
label: 'Dataset 2',
backgroundColor: 'rgba(66,139,202,0.5)',
borderColor: 'rgba(66,139,202,1)',
borderWidth: 2,
data: [
7,2,3,1,5,2,1
]
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
}
}
}
myChart = new Chart(ctx,config);
On the page they are directed to, I'd like to grab the GET data and construct a new Chart.

You can exclude the extra properties that Chart.js adds. E.g.:
JSON.stringify(myChart.config, function(key, value) {
if (key === '_meta') return undefined;
else return value;
}

Related

Representing multiple subsections within a section of a doughnut chart Chart.js

I am currently trying to create a doughnut chart that represents a projects completion with 2 mains sections; complete and incomplete. is there any way that I can make it so that the complete sections is split into multiple subsections which display peoples usernames when hovered without cluttering the legend?
Beneath is an artistic rendition because I feel like I haven't given enough information.
You can use the generateLabels function as described here.
Please take a look at below runnable sample code and see how it works.
var labels = ['Incomplete', 'Sam', 'Claudia', 'Kevin', 'Sonia', 'Kate'];
var data = [14, 5, 4, 3, 7, 5];
new Chart('myChart', {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: labels.map((l, i) => i ? 'yellow' : 'lightblue'),
weight: 0.6
}]
},
options: {
plugins: {
legend: {
labels: {
generateLabels: () => [{
text: 'Incomplete',
fillStyle: 'lightblue',
strokeStyle: 'lightblue',
},
{
text: 'Complete',
fillStyle: 'yellow',
strokeStyle: 'yellow',
}]
}
}
}
}
});
canvas {
max-height: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

How to compare one value to another in chartJS

I have been working on a broadband management website.I want to show the user how much data he/she has used.For example if the total data they have in their name is 300GB.If they have used 150GB the remaining is 150GB right?.How to do i visualize this using a doughnut chart,Using ChartJS.
I have some code going but im not sure how to accomplish this please help me out
var ctx = document.getElementById('myChart').getContext('2d');
var constdata=document.getElementById("constantdata").textContent;
var data=document.getElementById("data").textContent;
console.log(data);
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'doughnut',
// The data for our dataset
data: {
datasets: [{
label: 'My First dataset',
backgroundColor: ['red','green'],
borderColor: 'rgb(255, 99, 132)',
data: [300,150] //300 being the total data,150 being the data used
}]
},
// Configuration options go here
options: {}
But the above code isnt working out.Assume a doughnut chart,If the used data is 150GB(out of 300).The doughnut
chart must be like image1(please refer image 1)
But im getting image2(please refer image 2)
https://i.stack.imgur.com/nFTym.png //image 1
https://i.stack.imgur.com/MG99s.png //image 2
Assuming that the used data should appear in red, data should be defined as follows:
data: [used, total - used]
Please have a look at your amended code sample below.
const total = 300;
const used = 100;
var chart = new Chart(document.getElementById('myChart'), {
type: 'doughnut',
data: {
datasets: [{
label: 'My First dataset',
backgroundColor: ['red', 'green'],
borderColor: 'rgb(255, 99, 132)',
data: [used, total - used]
}]
},
options: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

problem with multiple datasets in chart.js

I'm trying to use chart.js to create a bar chart that shows the number of ad impressions in an ad buy by publication. The desired chart would show a bar for each publication representing the number of impressions for the ad on that website.
I thought that this needs to happen as multiple datasets, one for each publication, where each dataset contains one data point. Here's the code I'm using for this approach:
var chartData_webbanner_300x600 = {
labels: ["Publication 1", "Publication 2"],
datasets: [
{
label: "Publication 1",
backgroundColor: "#971317",
data: [30000]
},
{
label: "Publication 2",
backgroundColor: "#0b72ba",
data: [40000]
},
]
};
window.onload = function() {
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
window.myBar = new Chart(ctx_webbanner_300x600, {
type: 'bar',
data: chartData_webbanner_300x600,
options: {
title: {
display: true,
text: 'Web Banner Impressions'
},
responsive: true,
}
});
}; //window.onload = function()
The resulting chart only shows one bar. Here's a screenshot:
I also tried this as a single dataset, but had no luck there. This is the approach I tried with that:
var chartData_webbanner_300x600 = {
labels: ["Total Impressions"],
datasets: [
{
label: ["Publication 1", "Publication 2"],
backgroundColor: ["#971317","#0b72ba"],
data: [30000,40000]
}
]
};
window.onload = function() {
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
window.myBar = new Chart(ctx_webbanner_300x600, {
type: 'bar',
data: chartData_webbanner_300x600,
options: {
title: {
display: true,
text: 'Web Banner Impressions'
},
responsive: true,
}
});
}; //window.onload = function()
Here's how that is displaying (with no bars):
Please let me know if you have any ideas on what I'm doing wrong. Thank you for taking the time to help!
I was able to get it working with this code:
var graphData = {
labels: ['Publication 1', 'Publication 2'],
datasets: [{
label: 'Impressions',
data: [30000, 40000],
backgroundColor: [
"#971317",
"#0b72ba"
],
}, ]
};
var ctx_webbanner_300x600 = document.getElementById('chart_webbanner_300x600').getContext('2d');
var chr = new Chart(ctx_webbanner_300x600, {
data: graphData,
type: 'bar',
options: {
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true // minimum value will be 0.
}
}]
}
}
});
This is based on what I found here Setting specific color per label in chart.js and here How to set max and min value for Y axis - which overcame a problem where the scale was starting at the lowest value in my data set.

Dynamically populating data into chart in Chart.js

I have few charts ready in chart.js. I am trying to put the data that I have fetched through JSON file. How do I change the chart data automatically in a chart? I am getting json data from URL.
chartData1:{
labels: ["01 Jan","02 Jan","03 Jan","04 Jan","05 Jan","06
Jan","07 Jan"],
datasets: [{
label: "s1",
data:
[100,0,1,0,0,1,0,0,0,1,2,3,0,0,0,0,1,1,1,0,0,0,2,1,1,0,1,3,2,1,0],
fill:false,
borderColor: 'Orange',
lineTension:0,
borderWidth:2,
radius:2
},
{
label: "s2",
data:
[2,3,4,1,4,5,3,2,0,1,0,3,5,6,3,7,2,0,5,3,1,2,3,1,0,5,4,5,8,6,2],
fill:false,
borderColor: 'Violet',
lineTension:0,
borderWidth:2,
radius:2
}
]
},
"line-chart" is the id of the <canvas> where you want to display chart.
Try with this.
var chart1 = document.getElementById("line-chart").getContext("2d");
window.myLine = new Chart(chart1).Line(chartData1, {
responsive: true,
scaleLineColor: "rgba(0,0,0,.2)",
scaleGridLineColor: "rgba(0,0,0,.05)",
scaleFontColor: "#c5c7cc"
});

ChartJS Update specific bar's background colour

I would like to update specific column background colour but I couldn't do this. Seem like it is very easy but all the solution I tried out from google doesn't work. The code is as below.
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels : ["A","B","C","D","E"],
datasets: [{
data : [<?php echo $graph_data;?>],
backgroundColor: "rgba(0,0,220,0.5)",
borderColor: "rgba(0,0,220,1)",
borderWidth: 2
}]
}
});
//I would like to achieve something like this, let's say change the first and second bar's background color
myChart.datasets[0].bars[0].fillColor = "rgba(220,0,0,0.5)";
myChart.datasets[0].bars[1].fillColor = "rgba(220,0,0,0.5)";
myChart.update();
I had an old code which run succesfully under version 1.0.1-beta.4, but now I world like to use the latest version 2.5.0, and then I faced this issue.
Thanks for any helps!
You can just pass an array to the backgroundColor bar chart dataset property (instead of a single color) where the position in the array maps to the position in the data array.
For example, if you have 3 bars and want all 3 to be a different color, just pass an array to backgroundColor where all 3 elements have a different color value.
var ctx = document.getElementById("canvas").getContext("2d");
var myBar = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Car", "Bike", "Walking"],
datasets: [{
label: 'Fuel',
backgroundColor: [
chartColors.red,
chartColors.blue,
chartColors.yellow],
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
]
}]
},
options: {
title: {
display: true,
text: "Chart.js - Different Bar Colors"
},
tooltips: {
mode: 'index',
intersect: false
},
legend: {
display: false,
},
responsive: true,
}
});
Here is a codepen example demonstrating this.