I have one C# variable "value" that I want to pass into JavaScript Chartjs data object. It renders the chart but does not include the two #p values. See code source below:
cshtml file:
#{
int p1 = 43;
int p2 = 45;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div style="width: 400px;">
<canvas id="lineChart" width="400" height="400"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="main.js"></script>
</body>
</html>
javascript file:
var chart = document.getElementById("lineChart");
var data = {
labels: [2012, 2013, 2014, 2015, 2016, 2017],
datasets: [
{
label: "My Chart Label",
fill: false,
lineTension: 0.1,
data: ['(#p1)', '(#p2)', 50, 48, 47, 52]
}
]
};
var lineChart = new Chart(chart,
{
type: 'line',
data: data
}
);
How can I write it so that it works?
You can do
<script type="text/javascript">
var p1 = #p1, p2= #p2;
</script>
and use p1, p2.
var data = {
labels: [2012, 2013, 2014, 2015, 2016, 2017],
datasets: [
{
label: "My Chart Label",
fill: false,
lineTension: 0.1,
data: [p1, p2, 50, 48, 47, 52]
}
]
};
In this case you don't have to use hidden html fields and you can expand your code to use more field like
var tempObj ={
tempData: "",
otherData:"",
moreData: ""
}
Something like below
View:
#{
var p1 = 43;
var p2 = 45
}
<input type="hidden" id="PassingToJavaScript1" value=#p1>
<input type="hidden" id="PassingToJavaScript2" value=#p2>
JavaScript:
var p1 = document.getElementById('PassingToJavaScript1').value;
var p2 = document.getElementById('PassingToJavaScript2').value;
Use a hidden field which will hold the value and then read the hidden field's value from JavaScript.
Example:
#{
int p = 43;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div style="width: 400px;">
<canvas id="lineChart" width="400" height="400"></canvas>
<input type="hidden" id="someId" value="#p" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="main.js"></script>
</body>
</html>
JS
var chart = document.getElementById("lineChart");
var hiddenFieldValue = document.getElementById("someId").value;
var data = {
labels: [2012, 2013, 2014, 2015, 2016, 2017],
datasets: [
{
label: "My Chart Label",
fill: false,
lineTension: 0.1,
data: ['(hiddenFieldValue)', 45, 50, 48, 47, 52] // Not really sure how to format the data but you get main idea...
}
]
};
var lineChart = new Chart(chart,
{
type: 'line',
data: data
}
);
Related
I want to show the percentage distribution in pie chart. My current chart is perfect, except it does not have percentage labels. How to add percentage.
my code looks like;
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>
<script>
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [55, 49, 44, 24, 15];
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
new Chart("myChart", {
type: "pie",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues
}]
},
options: {
title: {
display: true,
text: "World Wide Car Production"
}
}
});
</script>
</body>
</html>
You just need to import some <script> from chart js. and then just modify little your code as below;
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
</head>
<body>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>
<script>
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [55, 49, 44, 24, 15];
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
var ctx = document.getElementById("myChart").getContext('2d');
var myChart =new Chart(ctx, {
type: "pie",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues
}]
},
options:{
tooltips: {
enabled: true
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = ctx.dataset._meta[0].total;
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
},
color: '#fff',
}
},
title: {
display: true,
text: "World Wide Car Production"
}
}
});
</script>
</body>
</html>
What I'm trying now is if I have 1 chart and then, when I click on a button with the "onchange" function, it'll display several chart. But when I'm clicking back, I have the chart I want but there is still the "legend" of the 2nd chart in the top of the 1st chart.
Is there a way to remove it ? I've found options: { legend: { display: false } but it remove the legend for all the chart.
Here is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
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', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {}
});
function toggleCategories(e){
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
}
chart.update();
}
</script>
</body>
</html>
Cordially
Chart.js highly depends on its data. Therefore, the easiest way is just dynamically populating the necessary data to your chart whenever you need it. This should add and remove the legend as expected. However, don't forget updating your chart on data change.
Let's add some code to get an idea about it, since basically you're actually doing it - but just a little bit wrong.
The data of your chart is stored in dataset. As we can see you have 2 entries whereas the 2nd one is just an object containing a boolean property (fill). Therefore, it's displaying undefined in your legend at the very beginning.
datasets: [{
label: 'My test1',
fill: false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {
fill: false
}]
However, when toggling the the checkbox it looks fine, since you're overwriting everything within your toggleCategories as seen below.
function toggleCategories(e) {
if (e.target.checked) {
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
...
}
chart.update();
}
But taking a closer look to else shows what's going on here.
// Those 3 lines just reset on index 1, it doesn't get deleted
chart.data.datasets[1].label = '';
chart.data.datasets[1].data = '';
chart.data.datasets[1].borderColor = '';
So in order to get rid of the 2nd legend when you only want 1, you simply have to remove the object of dataset[1] and re-add it whenever you need it.
You might want to look into this fiddle for a fully working example:
It could be a solution?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div class="row mt-3">
<div class="col-md-12">
<div>
<h5 id="legend" style="text-align: center;">My test 1</h5>
</div>
<div style="width:75%; margin: 0 auto;">
<canvas id="myChart"></canvas>
</div>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="checkBox" onchange="toggleCategories(event)">
<label class="form-check-label" for="checkBox">Catégories</label>
</div>
</div>
</div>
<script>
var test1 = [0, 10, 5, 2, 20, 30, 45, 60, 43, 22, 11, 23];
var test2 = [90, 80, 75, 62, 50, 40, 35, 11, 2, 24, 28, 34];
var test3 = [90, 10, 90, 10, 50, 40, 23, 62, 13, 32, 11, 13];
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', 'test3', 'test4', 'test5', 'test6', 'test7', 'test9', 'test10', 'test11', 'test12'],
datasets: [{
label: 'My test1',
fill : false,
borderColor: 'rgb(255, 99, 132)',
data: test1,
}, {fill : false
}]
},
// Configuration options go here
options: {legend:{display: false}}
});
function toggleCategories(e){
if (e.target.checked) {
changeLegendOnCl();
chart.data.datasets[0].label = 'My test2';
chart.data.datasets[0].data = test2;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test3';
chart.data.datasets[1].data = test3;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
} else {
document.getElementById("legend").innerHTML = "My test 1";
chart.data.datasets[0].label = 'My test1';
chart.data.datasets[0].data = test1;
chart.data.datasets[0].borderColor = 'rgb(255, 99, 132)';
chart.data.datasets[1].label = 'My test1';
chart.data.datasets[1].data = test1;
chart.data.datasets[1].borderColor = 'rgb(255, 99, 132)';
}
chart.update();
}
function changeLegendOnCl(){
document.getElementById("legend").innerHTML = "My test 2"+" "+"My test 3";
}
</script>
</body>
</html>
Hi guys i am using ChartJS for creating pie charts,it is pretty good.In my project i have to create many pie charts, all the charts will have the same labels and background color.In the code given below i am giving the backgroundColor and label while creating the pie charts individually.Is there any way to make label and background color common for all the charts.
<!DOCTYPE html>
<html>
<head>
<title> ChartJS tutorial </title>
<style type="text/css">
#pie-charts-wrapper{
width:1000px;
margin-left:auto;
margin-right:auto;
}
.pie-chart-wrapper{
width:500px;
height:300px;
box-sizing:border-box;
float:left;
padding:20px;
}
</style>
</head>
<body>
<div id="pie-charts-wrapper">
<div class="pie-chart-wrapper">
<canvas id="pieChart1" width="500px" height="300" ></canvas>
</div>
<div class="pie-chart-wrapper">
<canvas id="pieChart2" width="500px" height="300" ></canvas>
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" ></script>
<script type="text/javascript">
var ctx1 = document.getElementById("pieChart1");
var ctx2 = document.getElementById("pieChart2");
var data1 = {
labels: ['Signed','Not Signed'],
datasets: [{
backgroundColor:['#1abc9c','#34495e'],
data: [10, 25],
}],
};
var data2 = {
labels: ['Signed','Not Signed'],
datasets: [{
backgroundColor:['#1abc9c','#34495e'],
data: [15, 2]
}],
};
var myPieChart1 = new Chart(ctx1,{
type: 'pie',
data: data1
});
var myPieChart2 = new Chart(ctx2,{
type: 'pie',
data: data2
});
</script>
</body>
</html>
If speaking technically then yes, there is a way. Though it's not recommended, as that's not how ChartJS meant to work, therefore no built-in functionality either.
To accomplish this you would rather go for kind of a hacky solution, which is to use a plugin, like the following :
Chart.plugins.register({
beforeInit: function(chart) {
chart.data.labels = ['Signed', 'Not Signed'];
chart.data.datasets[0].backgroundColor = ['#1abc9c', '#34495e'];
}
});
* add this at the beginning of your script
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
Chart.plugins.register({
beforeInit: function(chart) {
chart.data.labels = ['Signed', 'Not Signed'];
chart.data.datasets[0].backgroundColor = ['#1abc9c', '#34495e'];
}
});
var ctx1 = document.getElementById("pieChart1");
var ctx2 = document.getElementById("pieChart2");
var data1 = {
datasets: [{
data: [10, 25],
}]
};
var data2 = {
datasets: [{
data: [15, 2]
}]
};
var myPieChart1 = new Chart(ctx1, {
type: 'pie',
data: data1
});
var myPieChart2 = new Chart(ctx2, {
type: 'pie',
data: data2
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="pieChart1" width="500px" height="300"></canvas>
<canvas id="pieChart2" width="500px" height="300"></canvas>
Tested versions:
Google Chrome - 56.0.2924.87
Mozilla Firefox - 51.0.1 (32-bit)
While developing my app in Chrome, I was able to insert a pie graphic with legends beneath it. But some time after I went to that page again and the graph did not render anymore. Tried it in Firefox and it rendered.
So by my tests I was able to detect that by updating the Chart.js version from 0.2.0 to 2.5.0 it made impossible for Chrome to render the graph.
Is it true that the only Chart.JS version to work in Chrome is the 0.2.0, or my tests are wrong?
TESTS:
Using Chart.JS v. 0.2.0 in Chrome
var pieData = [{
value: 20,
color: "#878BB6",
},
{
value: 40,
color: "#4ACAB4",
},
{
value: 10,
color: "#FF8153",
},
{
value: 30,
color: "#FFEA88",
}
];
// Get the context of the canvas element we want to select
var myChart = document.getElementById("myChart").getContext("2d");
new Chart(myChart).Pie(pieData);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
</head>
<body>
<script>
</script>
<h1>Chart.js Sample</h1>
<canvas id="myChart" width="600" height="400"></canvas>
</body>
</html>
Using Chart.JS v. 2.5.0
var pieData = [{
value: 20,
color: "#878BB6"
},
{
value: 40,
color: "#4ACAB4"
},
{
value: 10,
color: "#FF8153"
},
{
value: 30,
color: "#FFEA88"
}
];
// Get the context of the canvas element we want to select
var ctx = document.getElementById("myData").getContext("2d");
//new Chart(ctx).Pie(pieData);
/* New way to instantiate so that it do not thows Uncaught
TypeError: (intermediate value).Pie is not a function" */
var myPieChart = new Chart(ctx, {
type: 'pie',
data: pieData
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js" type="text/javascript"></script>
</head>
<body>
<script>
</script>
<h1>Chart.js Sample</h1>
<canvas id="myData" width="600" height="400"></canvas>
</body>
</html>
Your data structure for version 2.5.0 is completely wrong, it needs to look more like this (if it was working for you in Firefox using the shown data structure then I have no idea why, because it shouldn't have):
var pieData = {
labels: ["Purple", "Green", "Orange", "Yellow"],
datasets: [
{
data: [20, 40, 10, 30],
backgroundColor: [
"#878BB6",
"#4ACAB4",
"#FF8153",
"#FFEA88"
]
}]
};
Notice how it's no longer an array of objects, but an object containing arrays. Also the direct properties of pieData are labels and datasets and then datasets is split into the values and the background color.
Link to the Pie Chart data structure documentation for reference: Chart JS Documentation
JSFiddle example: https://jsfiddle.net/0vh3xhsw/2/
var pieData = {
labels: ["Purple", "Green", "Orange", "Yellow"],
datasets: [{
data: [20, 40, 10, 30],
backgroundColor: [
"#878BB6",
"#4ACAB4",
"#FF8153",
"#FFEA88"
]
}]
};
// Get the context of the canvas element we want to select
var ctx = document.getElementById("myData").getContext("2d");
//new Chart(ctx).Pie(pieData);
/* New way to instantiate so that it do not thows Uncaught
TypeError: (intermediate value).Pie is not a function" */
var myPieChart = new Chart(ctx, {
type: 'pie',
data: pieData
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js" type="text/javascript"></script>
</head>
<body>
<script>
</script>
<h1>Chart.js Sample</h1>
<canvas id="myData" width="600" height="400"></canvas>
</body>
</html>
[Update: This may have been fixed in version 2.1.5]
In Chart.js version 1 I used to be able to set the spacing between the scale lines on a radar chart. The desired behaviour was lines from 0 to 100 in steps of 5. I used the following version 1 options:
{
scaleOverride: true,
scaleStartValue: 0,
scaleSteps: 20,
scaleStepWidth: 5
}
Since upgrading to version 2 (2.1.4) I can't seem to get the same behaviour. Below is a minimal chart based on the documentation for a radar chart with my best guess for how it should work. The stepSize argument seems to be ignored.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Radar Chart Test</title>
<script src="Chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400px" height="400px"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
datasets: [
{
label: "My First dataset",
data: [65, 59, 90, 81, 56, 55, 40]
},
{
label: "My Second dataset",
data: [28, 48, 40, 19, 96, 27, 100]
}
]
};
var myChart = new Chart(ctx, {
type: 'radar',
data: data,
options: {
scale: {
ticks: {
min: 0,
max: 100,
stepSize: 5,
}
}
}
});
</script>
</body>
</html>
Any thoughts most appreciated.