How to get values for a chart with JavaScript in Django? - javascript

I created an application with Django. In this system, there is an approval system. I created an ApprovalProcess model and it has a beginning_date field. I crated a chart for showing how many approval processes are started on which day? But I cannot fill this chart.
But I cannot figure it out how can I get approval process values as my data? the data that I want to display is all_approvals in my views.
models.py
class ApprovalProcess(models.Model):
id = models.AutoField(primary_key=True)
user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter')
doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True)
begin_date = models.DateTimeField(auto_now=True)
end_date = models.DateTimeField(auto_now=True)
status = models.IntegerField(default=0)
highest_rank = models.IntegerField(default=0)
last_approved = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='last_approved')
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True)
views.py
def approval_context_processor(request):
if request.user.is_authenticated:
current_user = request.user
rank_priority = RankPriority.objects.filter(rank=current_user.rank)
priority = rank_priority[0].priority
pend_list = ApprovalProcess.objects.filter(status=priority)
submit_list = ApprovalProcess.objects.filter(user_id=current_user)
userP = UserProfile.objects.get_or_create(username=current_user)
customer_list = Customer.objects.filter(company=userP[0].company)
all_approvals = ApprovalProcess.objects.filter(user_id__company=request.user.company)
approved_reports = 0
waiting_reports = 0
for submit in submit_list:
if submit.status - submit.highest_rank == 1:
approved_reports += 1
else:
waiting_reports += 1
else:
pend_list = 0
submit_list = 0
context = {
'pend_list': pend_list,
'submit_list': submit_list,
'approved_reports': approved_reports,
'waiting_reports': waiting_reports,
'customer_list': customer_list,
'all_approvals': all_approvals
}
return context
chart
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<div class="card-head-row">
<div class="card-title">User Statistics</div>
<div class="card-tools">
</div>
</div>
</div>
<div class="card-body">
<div class="chart-container" style="min-height: 375px">
<canvas id="statisticsChart"></canvas>
</div>
<div id="myChartLegend"></div>
</div>
</div>
</div>
...
...
var ctx = document.getElementById('statisticsChart').getContext('2d');
var statisticsChart = new Chart(ctx, {
type: 'line',
data: {
labels: [
],
datasets: [ {
label: "Approval Processes",
borderColor: '#f3545d',
pointBackgroundColor: 'rgba(243, 84, 93, 0.6)',
pointRadius: 0,
backgroundColor: 'rgba(243, 84, 93, 0.4)',
legendColor: '#f3545d',
fill: true,
borderWidth: 2,
data: [100, 184, 250, 203, 210, 231, 240, 278, 252, 312, 320, 374]
}, ]
},
options : {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
bodySpacing: 4,
mode:"nearest",
intersect: 0,
position:"nearest",
xPadding:10,
yPadding:10,
caretPadding:10
},
layout:{
padding:{left:5,right:5,top:15,bottom:15}
},
scales: {
yAxes: [{
ticks: {
fontStyle: "500",
beginAtZero: false,
maxTicksLimit: 5,
padding: 10
},
gridLines: {
drawTicks: false,
display: false
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent"
},
ticks: {
padding: 10,
fontStyle: "500"
}
}]
},
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend html-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><span style="background-color:' + chart.data.datasets[i].legendColor + '"></span>');
if (chart.data.datasets[i].label) {
text.push(chart.data.datasets[i].label);
}
text.push('</li>');
}
text.push('</ul>');
return text.join('');
}
}
});

i don't know which data you want to get from ApprovalProcess model but suppose you want to get highest_rank field to pass it to data chart
you code will be like this :
import json
def approval_context_processor(request):
if request.user.is_authenticated:
current_user = request.user
rank_priority = RankPriority.objects.filter(rank=current_user.rank)
priority = rank_priority[0].priority
pend_list = ApprovalProcess.objects.filter(status=priority)
submit_list = ApprovalProcess.objects.filter(user_id=current_user)
userP = UserProfile.objects.get_or_create(username=current_user)
customer_list = Customer.objects.filter(company=userP[0].company)
all_approvals = ApprovalProcess.objects.filter(user_id__company=request.user.company)
approved_reports = 0
waiting_reports = 0
for submit in submit_list:
if submit.status - submit.highest_rank == 1:
approved_reports += 1
else:
waiting_reports += 1
else:
pend_list = 0
submit_list = 0
context = {
'pend_list': pend_list,
'submit_list': submit_list,
'approved_reports': approved_reports,
'waiting_reports': waiting_reports,
'customer_list': customer_list,
'all_approvals': json.dumps([e.highest_rank for e in all_approvals])
}
return context
then you get your data in template like this :
var ctx = document.getElementById('statisticsChart').getContext('2d');
var statisticsChart = new Chart(ctx, {
type: 'line',
data: {
labels: [
],
datasets: [ {
label: "Approval Processes",
borderColor: '#f3545d',
pointBackgroundColor: 'rgba(243, 84, 93, 0.6)',
pointRadius: 0,
backgroundColor: 'rgba(243, 84, 93, 0.4)',
legendColor: '#f3545d',
fill: true,
borderWidth: 2,
data: {{ all_approvals|safe }}
}, ]
},
options : {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
bodySpacing: 4,
mode:"nearest",
intersect: 0,
position:"nearest",
xPadding:10,
yPadding:10,
caretPadding:10
},
layout:{
padding:{left:5,right:5,top:15,bottom:15}
},
scales: {
yAxes: [{
ticks: {
fontStyle: "500",
beginAtZero: false,
maxTicksLimit: 5,
padding: 10
},
gridLines: {
drawTicks: false,
display: false
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent"
},
ticks: {
padding: 10,
fontStyle: "500"
}
}]
},
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend html-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><span style="background-color:' + chart.data.datasets[i].legendColor + '"></span>');
if (chart.data.datasets[i].label) {
text.push(chart.data.datasets[i].label);
}
text.push('</li>');
}
text.push('</ul>');
return text.join('');
}
}
});

Related

Creating charts

I need to make a chart at the level with a row in the table, are there any tips on how to implement this enter image description here
I need the chart lines to match the row level in the table
and this code draws a separate chart
const diag = () => {
document.getElementById("canvasic").innerHTML = ' ';
document.getElementById("canvasic").innerHTML = '<canvas id="densityChart" className="canav"></canvas>';
densityCanvas = document.getElementById("densityChart");
//remove canvas from container
Chart.defaults.global.defaultFontFamily = "Arial";
Chart.defaults.global.defaultFontSize = 16;
var densityData = {
label: 'CallVol',
data:calloiList1,
backgroundColor: 'rgba(0,128,0, 0.6)',
borderColor: 'rgba(0,128,0, 1)',
borderWidth: 2,
hoverBorderWidth: 0
};
var densityData1 = {
label: 'PutVol',
data:calloiList3 ,
backgroundColor: 'rgba(255,0,0, 0.6)',
borderColor: 'rgba(255,0,0, 1)',
borderWidth: 2,
hoverBorderWidth: 0
};
var chartOptions = {
scales: {
yAxes: [{
barPercentage: 0.5
}]
},
elements: {
rectangle: {
borderSkipped: 'left',
}
}
};
var barChart = new Chart(densityCanvas, {
type: 'horizontalBar',
data: {
labels: calloiList4,
datasets: [densityData,densityData1],
},
options: chartOptions
}
);
}
enter image description here

Unable to display multiple line charts in javascript

I am very new to java-script and was trying to learn how to add multiple line charts to my web UI. But unfortunately I am stuck with a problem, I am unable to add multiple line charts to my web UI.
I am unable to understand what I am doing wrong. I tried several approaches but couldn't find the solution.
Appreciate the help!
Below is my code for your reference.
var xValues = [50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150];
var yValues = [7, 8, 8, 9, 9, 9, 10, 11, 14, 14, 15];
function displayPanel(i) {
var panel = document.getElementById('panel');
panel.innerHTML += `
<div class="row">
<div class="column">
<form>
<label id="paramname_${i}" for="paramvalue">${i}</label>
<input type="text" id="paramvalue_${i}" name="param" value=${i} readonly>
</form>
</div>
<div id="chart_${i}" class="column">
<canvas id="myChart${i}" style="width:100%;max-width:600px"></canvas>
</div>
</div>`;
new Chart("myChart" + i, {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 6,
max: 16
}
}],
}
}
});
new Chart("myChart" + i, {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 6,
max: 16
}
}],
}
}
});
}
for (i = 0; i < 2; i++) {
displayPanel(i);
}
<style>.column {
float: left;
align-self: right;
width: 50%;
padding: 10px;
}
.row {
content: "";
clear: both;
display: table;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<!DOCTYPE html>
<html>
<body>
<div id="panel"></
----------
div>
</body>
function addParamsToPanel(parameter, paramValue, isDisplay, i) {
console.log("XXXX" + parameter);
if (isDisplay) {
displayPanel(parameter, paramValue,i);
}
}
function updatePanel(paramList, valueList) {
param = paramList.toString().split(',');
paramValue = valueList.toString().split(',');
for (var i = 0; i < param.length; i++) {
var p = document.createElement("div");
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.id = param[i];
p.appendChild(checkBox);
p.appendChild(label);
document.getElementById("cboxes").appendChild(p);
label.appendChild(document.createTextNode(param[i]));
document.getElementById(param[i]).checked = true;
addParamsToPanel(param[i], paramValue[i], document.getElementById(param[i]).checked, i);
}
}
function displayPanel(parameter, paramValue, i) {
var panel = document.getElementById('panel');
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var newChart = 'paramChart_' + parameter;
panel.innerHTML += `
<div class="row">
<!--div class="col-md-9 col-lg-10 col-sm-11"-->
<div class="column">
<form>
<label id="paramname_${parameter}" for="paramvalue">${parameter}</label>
<input type="text" id="paramvalue_${parameter}" name="param" value=${paramValue} readonly>
</form>
</div>
<div id="chart_${i}" class="column">
<canvas id=${newChart} style="width:100%;max-height:100px;max-width:700px;border: solid;rgb(4, 31, 65);"></canvas>
</div>
`;
console.log(newChart.value);
var chart = new Chart(newChart, {
type: "line",
data: {
labels: xValues,
datasets: [{
//label: 'set of ' + parameter,
fill: false,
//lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues,
showLine: true,
spanGaps: true
}]
},
options: {
legend: { display: false }
}
});
chartMap.set(newChart, chart);
chart.data.datasets[0].data.push(i.value);
chart.data.labels.push(time);
chart.update();
}
updatePanel(paramList, valueList);
It seems like that when you add a new part to the inner html it has some weird behaviour with chart.js, if you first make all the divs with forms and canvasses and then create the charts it works fine:
var xValues = [50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150];
var yValues = [7, 8, 8, 9, 9, 9, 10, 11, 14, 14, 15];
function displayPanel(i) {
var panel = document.getElementById('panel');
panel.innerHTML += `
<div class="row">
<div class="column">
<form>
<label id="paramname_${i}" for="paramvalue">${i}</label>
<input type="text" id="paramvalue_${i}" name="param" value=${i} readonly>
</form>
</div>
<div id="chart_${i}" class="column">
<canvas id="myChart${i}" style="width:100%;max-width:600px"></canvas>
</div>`;
}
function createChart(i) {
new Chart("myChart" + i, {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 6,
max: 16
}
}],
}
}
});
}
function createUI(k) {
for (i = 0; i < k; i++) {
displayPanel(i);
}
for (i = 0; i < k; i++) {
createChart(i);
}
}
createUI(3)
<style>.column {
float: left;
align-self: right;
width: 50%;
padding: 10px;
}
.row {
content: "";
clear: both;
display: table;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<!DOCTYPE html>
<html>
<body>
<div id="panel"></div>
</body>

How to plot a single value with line in line chart graph using charts.js?

I need to plot a single value in line chart. Currently i am using charts.JS library for line graph purpose.
The data will be varied some times i'll get the single data inside the data set at that time i need to plot the single value with line in the line chart.
I tried with the charts.js annotation plugin but it wasn't met my requirements. which is like it wis overlapping the plotted point in the graph area.
CODE WHICH I HAD TRIED
createLineChart() {
this.lineChart = new Chart(this.lineCanvas.nativeElement, {
type: "line",
data: {
labels:[],
datasets: [
{
fill: false,
backgroundColor: "#0168FF",
borderColor: "#0168FF",
pointBackgroundColor: "white", // wite point fill
pointBorderWidth: 1, // point border width
lineTension: 0,
pointBorderColor: "blue",
pointRadius: 4,
},
],
},
options: {
scales: {
yAxes: [
{
ticks: {
padding: 20,
beginAtZero: true,
min: 0,
stepSize: 100,
},
gridLines: {
drawBorder: false,
},
},
],
xAxes: [
{
// offset: true,
ticks: {
display: false,
//beginAtZero: true,
min: 0,
},
gridLines: {
zeroLineColor: "transparent",
drawBorder: false,
display: false,
},
//offset:true,
},
],
legend: {
display: false,
},
tooltips: {
enabled: false,
},
},
drawTime: "afterDraw", // (default)
} as ChartOptions,
// plugins: [ChartAnnotation]
},
});
}
To generate dynamic data and plot in the graph area.
generateRandomDataSet(size) {
let yaxisArr = [];
let xaxisArr = [];
let random_data:any = this.getRandomData(size)
let maxYTickVal = Math.max.apply(Math, random_data.map((val) => {return val.yaxis}));
let maxVal = Math.ceil((maxYTickVal+1) / 10) * 10
for(let data of random_data) {
yaxisArr.push(data.yaxis)
xaxisArr.push(data.xaxis)
}
console.log("X-Axis array values : "+xaxisArr)
console.log("Y-Axis array values : "+yaxisArr)
this.lineChart.data.datasets[0].data = yaxisArr
this.lineChart.config.data.labels = []
this.lineChart.config.data.labels = xaxisArr
this.lineChart.config.options.scales.yAxes[0].ticks.max =maxVal
this.lineChart.config.options.scales.yAxes[0].ticks.stepSize = maxVal/2
this.lineChart.update()
}
getRandomData(arraySize) {
let data = []
for(var i=1; i<=arraySize; i++) {
let number = Math.floor(Math.random() * 200) + 1
data.push({'xaxis':i,'yaxis':number})
}
return data
}
with the above code i am getting like
what i need to have
You can define an animation.onComplete function as follows to draw the line in case a single data value is present.
animation: {
onComplete: e => {
var ctx = chart.chart.ctx;
var data = chart.config.data.datasets[0].data;
if (data[0] == null) {
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
var y = yAxis.getPixelForValue(data[1]);
ctx.save();
ctx.globalCompositeOperation='destination-over';
ctx.strokeStyle = 'blue'
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(xAxis.left, y);
ctx.lineTo(xAxis.right, y);
ctx.stroke();
ctx.restore();
}
}
},
This function expects the data array to be of format [null, <value>, null] in case a single value is present, otherwise it will be hard to horizontally center the data point (see this answer). It's up to you to change the generateRandomDataSet() function in a way that it provides such data.
Please have a look at your changed code below.
const chart = new Chart('line-chart', {
type: "line",
data: {
labels: ['', 'A', ''],
datasets: [{
data: [null, 120, null],
fill: false,
backgroundColor: "#0168FF",
borderColor: "#0168FF",
pointBackgroundColor: "white",
pointBorderWidth: 1,
lineTension: 0,
pointBorderColor: "blue",
pointRadius: 4,
}],
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
animation: {
onComplete: e => {
var ctx = chart.chart.ctx;
var data = chart.config.data.datasets[0].data;
if (data[0] == null) {
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
var y = yAxis.getPixelForValue(data[1]);
ctx.save();
ctx.globalCompositeOperation='destination-over';
ctx.strokeStyle = 'blue'
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(xAxis.left, y);
ctx.lineTo(xAxis.right, y);
ctx.stroke();
ctx.restore();
}
}
},
scales: {
yAxes: [{
ticks: {
padding: 20,
min: 0,
stepSize: 100
},
gridLines: {
drawBorder: false
}
}],
xAxes: [{
ticks: {
display: false
},
gridLines: {
zeroLineColor: "transparent",
drawBorder: false,
display: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas>

Update ChartJs chart using $scope in AngularJS

I'm having some issues when trying to update a chart's data using $scope.
I know there's a function to update charts myChart.update(); but I can't get to update the char when I put it in a $scope.
The following code gets the chart's data and then tries to update the chart. The problem comes at $scope.lineChart.update();. It looks like chartjs can't detect any changes.
The following code is executed after triggering a select, so the chart has an initial data and the following code just tries to update it.
This does not work: $scope.lineChart.update();
$scope.getLineChartMaxData().then(function () {
$scope.getLineChartMinData().then(function () {
$scope.lineChart.update();
});
});
The chart function:
$scope.fillLineChart = function () {
console.log("FILLING LINE CHART");
const brandProduct = 'rgba(0,181,233,0.5)'
const brandService = 'rgba(0,173,95,0.5)'
var data1 = $scope.lineChartMaxWeekData;
var data2 = $scope.lineChartMinWeekData;
var maxValue1 = Math.max.apply(null, data1)
var maxValue2 = Math.max.apply(null, data2)
var minValue1 = Math.min.apply(null, data1)
var minValue2 = Math.min.apply(null, data2)
var maxValue;
var minValue;
if (maxValue1 >= maxValue2) {
maxValue = maxValue1;
} else {
maxValue = maxValue2;
}
if (minValue1 >= minValue2) {
minValue = minValue2;
} else {
minValue = minValue1;
}
$scope.minValue = minValue;
$scope.maxValue = maxValue;
var ctx = document.getElementById("recent-rep-chart");
if (ctx) {
ctx.height = 250;
$scope.lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: $scope.lineChartMaxWeekLabels,
datasets: [{
label: 'Valor',
backgroundColor: brandService,
borderColor: 'transparent',
pointHoverBackgroundColor: '#fff',
borderWidth: 0,
data: data1
},
{
label: 'My Second dataset',
backgroundColor: brandProduct,
borderColor: 'transparent',
pointHoverBackgroundColor: '#fff',
borderWidth: 0,
data: data2
}
]
},
options: {
maintainAspectRatio: true,
legend: {
display: false
},
responsive: true,
scales: {
xAxes: [{
gridLines: {
drawOnChartArea: true,
color: '#f2f2f2'
},
ticks: {
fontFamily: "Poppins",
fontSize: 12
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
maxTicksLimit: 5,
stepSize: 50,
max: maxValue,
fontFamily: "Poppins",
fontSize: 12
},
gridLines: {
display: true,
color: '#f2f2f2'
}
}]
},
elements: {
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 4,
hoverBorderWidth: 3
}
}
}
});
}
};
UPDATE: $scope.lineChart.destroy(); works well, but I don't want to destroy the chart and build it again because it is built with another sizes.

How to use JSON data in creating a chart with chartjs?

In my controller I have an Action method that will find all questions in a table called Questions, and the answers for each question.
This Action is of type ContentResult that will return a result serialized in Json format.
public ContentResult GetData()
{
var datalistQuestions = db.Questions.ToList();
List<PsychTestViewModel> questionlist = new List<PsychTestViewModel>();
List<PsychTestViewModel> questionanswerslist = new List<PsychTestViewModel>();
PsychTestViewModel ptvmodel = new PsychTestViewModel();
foreach (var question in datalistQuestions)
{
PsychTestViewModel ptvm = new PsychTestViewModel();
ptvm.QuestionID = question.QuestionID;
ptvm.Question = question.Question;
questionlist.Add(ptvm);
ViewBag.questionlist = questionlist;
var agree = //query
var somewhatAgree = //query
var disagree = //query
int Agree = agree.Count();
int SomewhatAgree = somewhatAgree.Count();
int Disagree = disagree.Count();
ptvmodel.countAgree = Agree;
ptvmodel.countSomewhatAgree = SomewhatAgree;
ptvmodel.countDisagree = Disagree;
questionanswerslist.Add(ptvmodel);
ViewBag.questionanswerslist = questionanswerslist;
}
return Content(JsonConvert.SerializeObject(ptvmodel), "application/json");
}
Now, my problem is the pie chart is not being created and I don't quite know how to push the values to my data structure?
What should I be doing instead?
Here is my script:
#section Scripts {
<script type="text/javascript">
var PieChartData = {
labels: [],
datasets: [
{
label: "Agree",
backgroundColor:"#f990a7",
borderWidth: 2,
data: []
},
{
label: "Somewhat Agree",
backgroundColor: "#aad2ed",
borderWidth: 2,
data: []
},
{
label: "Disgree",
backgroundColor: "#9966FF",
borderWidth: 2,
data: []
},
]
};
$.getJSON("/PsychTest/GetData/", function (data) {
for (var i = 0; i <= data.length - 1; i++) {
PieChartData.datasets[0].data.push(data[i].countAgree);
PieChartData.datasets[1].data.push(data[i].countSomewhatAgree);
PieChartData.datasets[2].data.push(data[i].countDisagree);
}
var ctx = document.getElementById("pie-chart").getContext("2d");
var myLineChart = new Chart(ctx,
{
type: 'pie',
data: PieChartData,
options:
{
responsive: true,
maintainaspectratio: true,
legend:
{
position : 'right'
}
}
});
});
</script>
You need two arrays for creating your chart. One of them indicates titles and another one shows the number of each titles. You have titles in the client side, so you only need the number of each options and it could be fetched from a simple server method like:
[HttpGet]
public JsonResult Chart()
{
var data = new int[] { 4, 2, 5 }; // fill it up whatever you want, but the number of items should be equal with your options
return JsonConvert.SerializeObject(data)
}
The client side code is here:
var aLabels = ["Agree","Somewhat Agree","Disagree"];
var aDatasets1 = [4,2,5]; //fetch these from the server
var dataT = {
labels: aLabels,
datasets: [{
label: "Test Data",
data: aDatasets1,
fill: false,
backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
borderWidth: 1
}]
};
var opt = {
responsive: true,
title: { display: true, text: 'TEST CHART' },
legend: { position: 'bottom' },
//scales: {
// xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }],
// yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }]
//}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: dataT,
options: opt
});
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.7.1/Chart.min.js"></script>
<div Style="font-family: Corbel; font-size: small ;text-align:center " class="row">
<div style="width:100%;height:100%">
<canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas>
</div>
</div>
If you are still looking to use json for chart.js charts.
Here is a solution which fetch a json file and render it on chart.js chart.
fetch('https://s3-us-west-2.amazonaws.com/s.cdpn.io/827672/CSVtoJSON.json')
.then(function(response) {
return response.json();
})
.then(function(ids) {
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ids.map(function(id) {
return id.Label;
}),
datasets: [
{
label: "value2",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value2;
}),
},
{
label: "value",
//backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value;
}),
},
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Sample Json Data Chart'
}
}
});
});
see running code on jsfiddle here

Categories