cann't make Chart when convertting View MVC to PDF - model-view-controller

I am trying to convert the output of MVC view to PDF. I could do that by Rotativa pretty good by using this video
https://www.youtube.com/watch?v=VkHcG24nM8U
but there is still a problem. in the view I am creating a radar chart dynamically. which when the pdf is created it is missing. is it possible to make chart when converting view to PDF file?
This is the code for making Rotativa viewTo PDF
public async Task<IActionResult> PrintPDF(long wId, long cId, long pId, long aId, short no)
{
var result = await _accessmentFacad.GetAssessmentResultForUserByIdService.Execute(wId, cId, pId, aId, no);
return new ViewAsPdf("PrintPDF", result)
{
FileName ="sample.pdf",
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
PageSize = Rotativa.AspNetCore.Options.Size.A4,
};
}
and using this jquery radarchart code for creating the chart
<script>
var BeforeWorkshop = []; //these are javascript array variables
var AfterWorkshop = [];
#if(Model.ResultCategoriesDtos.Count>0)
{
foreach(var item in Model.ResultCategoriesDtos)
{
#:BeforeWorkshop.push(#item.Answer3_1);
#:AfterWorkshop.push(#item.Answer3_2);
}
}
var RadarChart = document.getElementById('radarchart').getContext('2d');
var chart = new Chart(RadarChart, {
type: 'radar',
data: {
labels: ["1Lesson", "2Lesson","3Lesson", "4Lesson", "5Lesson"],//x axis labels
datasets: [{
label: "First",
data: BeforeWorkshop,
fill: true,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 255)',
pointBackgroundColor: 'rgb(255, 99, 132)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)',
}
, {
label: "Second",
data: AfterWorkshop,
fill: true,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgb(54, 162, 235)',
pointBackgroundColor: 'rgb(54, 162, 235)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(54, 162, 235)'
}
]
},
// Configuration options
options: {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ": " + tooltipItem.yLabel;
}
}
}
}
});
</script>

Related

How to hide/show bars differentiate by a colors and by click on labels, using chartjs bar charts?

I am using chartjs to show one month attendance data, what I want to acheive is to show each day data with different colors like Present, absent and leave. I want labels on top and by click on that label user should be able to hide/show that particular label data, below is my code.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- HTML -->
<canvas id="chartJsDiv"></canvas>
<script>
function attendanceSummaryChart3(attendence)
{
var datasets = [];
var labels_data = [];
var num_of_hour = [];
var bar_colours = [];
var border_colr = [];
var real_data_count = attendence.length;
for (var i = 0; i < real_data_count; i++) {
var mydate = new Date(attendence[i].date);
var month = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"][mydate.getMonth()];
var str = mydate.getDate() + ' ' +month;
labels_data.push(str);
if(parseFloat(attendence[i].hours.replace(':','.')) < 6.00)
{
if(attendence[i].is_leave != null)
{
var applied_leave_type = attendence[i].is_leave_applied.leave_type.slug;
if(applied_leave_type == "work-from-home")
{
// Full hours in case work from home
num_of_hour.push('9');
bar_colours.push('RGB(25, 135, 84)');
border_colr.push('rgba(3, 126, 25, 0.85)');
// creating datasets
datasets.push({label: 'Work From Home', data: '9', backgroundColor: 'RGB(25, 135, 84)' });
}
else
{
// Leave applied
if(parseFloat(attendence[i].hours.replace(':','.')) == 0)
{
num_of_hour.push('-9');
bar_colours.push('RGB(25, 135, 84)');
border_colr.push('rgba(14, 8, 191, 0.8)');
// creating datasets
datasets.push({label: 'On Leave', data: '-9', backgroundColor: 'RGB(25, 135, 84)'});
}
else
{
num_of_hour.push(parseFloat(attendence[i].hours.replace(':','.')));
bar_colours.push('RGB(25, 135, 84)');
border_colr.push('rgba(14, 8, 191, 0.8)');
// creating datasets
datasets.push({label: 'Half Leave', data: parseFloat(attendence[i].hours.replace(':','.')), backgroundColor: 'RGB(25, 135, 84)'});
}
}
}
else
{
if(parseFloat(attendence[i].hours.replace(':','.')) == 0)
{
// If absent and no leave is applied
num_of_hour.push('-9');
bar_colours.push('RGB(255, 0, 0)');
border_colr.push('rgba(6, 108, 166, 0.8)');
// creating datasets
datasets.push({label: 'Absent (No Leave Applied)', data: '-9', backgroundColor: 'RGB(255, 0, 0)' });
}
else
{
// If present and didn't complete 06 hours in office
num_of_hour.push(parseFloat(attendence[i].hours.replace(':','.')));
bar_colours.push('RGB(255, 0, 0)');
border_colr.push('rgba(255, 99, 132, 1)');
// creating datasets
datasets.push({label: 'Present (Half Time)', data: parseFloat(attendence[i].hours.replace(':','.')), backgroundColor: 'RGB(255, 0, 0)' });
}
}
}
else
{
// Full hours
num_of_hour.push(parseFloat(attendence[i].hours.replace(':','.')));
bar_colours.push('RGB(0, 255, 0)');
border_colr.push('rgba(75, 192, 192, 1)');
// creating datasets
datasets.push({label: 'Present', data: parseFloat(attendence[i].hours.replace(':','.')), backgroundColor: 'RGB(25, 135, 84)' });
}
}
console.log(datasets);
const ctx = document.getElementById('chartJsDiv').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels_data,
datasets: [
{
label: ['Attendence'],
data: num_of_hour,
backgroundColor: bar_colours,
borderColor: border_colr,
}
]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
},
});
}
</script>
I am attaching a screenshot below currently I only have one label but I want multiple labels based on multiple colors bar
You need to use a second dataset to achieve this:
Then you can fill null values in both datasets where you dont use the values of that dataset, so null values on the places where value is negative in positive dataset and vice versa in other one.
Then you can use the property skipNull to make it so the bars dont take up space:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, null, 3, 5, null, 3],
backgroundColor: 'green'
},
{
label: '# of Points',
data: [null, -11, null, null, -3, null],
backgroundColor: 'red'
}
]
},
options: {
skipNull: true
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>
should be this part
label: ['Attendence', 'newLabel', 'xxx'],
under
const ctx = document.getElementById('chartJsDiv').getContext('2d');

How to externally trigger datalabels-plugin (active) - ChartJS

I'm playing with this code:
https://jsfiddle.net/netquik/e3jp2k5o/37/
First created a plugin to hightlight Labels (ticks) on x axis when hovering on chart bars (used mousemove for now). Then i tried trigger externally setActiveElements for chart and tooltip. And it seems to work as intended.
expected result
My problem is i can't find a way to "update" datalabels at the same time so it can show me datalabels. In the code you can see i tried manually enable some $context property of $datalabels with no luck. After setActiveElements externally i see in debugging that datalabels trigger itself after chart update and try
display: function (context) {
return context.active; // display labels if active
},
but even if the element in chart is "active" ti return a false context.active.
Could be a problem of interaction modes? Thanks for your help.
trigger result without datalabel
var SCRIPTOBJ = null;
var LABEL = ["Gino", "Samantha", "Vercingetorige"];
var DATA = [5, 28, 500];
var MAX = Math.max(...DATA);
var ctx = $('#stat');
Chart.defaults.font.size = 14;
Chart.register(ChartDataLabels);
var lastLabelH = null;
var stat = new Chart(ctx, {
type: 'bar',
data: {
labels: LABEL,
datasets: [{
minBarLength: 15,
barPercentage: 1,
label: '# VOTES',
data: DATA,
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(75, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
hoverBackgroundColor: [
'rgba(255, 99, 132, 1.0)',
'rgba(54, 162, 235, 1.0)',
'rgba(255, 206, 86, 1.0)',
'rgba(75, 192, 192, 1.0)',
'rgba(153, 102, 255, 1.0)',
'rgba(255, 159, 64, 1.0)'
],
borderWidth: 1
}]
},
plugins: [{
id: 'LabelHighlight',
beforeEvent(c, args, pluginOptions) {
const event = args.event;
if (event.type === 'mouseout') {
if (lastLabelH != null) {
//c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
c.update();
lastLabelH = null;
}
} else if (event.type === 'mousemove') {
if (c._active.length > 0) {
let labelindex = c._active[0].index;
if (c.scales.x._labelItems) {
let label = c.scales.x._labelItems[labelindex];
label.color = "rgba(255, 255, 64, 1)";
}
if (lastLabelH != null && lastLabelH != labelindex) {
if (c.scales.x._labelItems) {
c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
}
}
lastLabelH = labelindex;
} else {
if (lastLabelH != null) {
if (c.scales.x._labelItems) {
c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
}
lastLabelH = null;
}
}
}
}
}],
options: {
responsive: false,
interaction: {
mode: 'index',
intersect: true
},
/* onHover: function (event, elements, c) {
if (elements && elements.length) {
if (c._active.length > 0) {
let labelindex = c._active[0].index;
let label = c.scales.x._labelItems[labelindex];
label.color = "rgba(255, 255, 64, 1)";
lastLabelH = labelindex;
}
} else {
if (lastLabelH != null) {
c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
lastLabelH = null;
}
}
}, */
layout: {
padding: {
top: 50,
left: 0,
right: 0,
bottom: 0
}
},
indexAxis: 'x',
scales: {
x: {
beginAtZero: true,
ticks: {
display: true,
color: 'rgba(255, 159, 64, 1)',
autoSkip: false,
maxRotation: 90,
minRotation: 90,
labelOffset: -8,
textStrokeColor: 'rgba(0, 0, 0, 0.5)',
textStrokeWidth: '2',
font: {
weight: 'bold',
family: 'Arial',
size: 16
},
align: 'start'
}
},
y: {
max: MAX + 1,
beginAtZero: true,
ticks: {
color: 'rgba(255, 159, 64, 1)',
stepSize: 1
}
}
},
plugins: {
legend: {
display: false
},
datalabels: {
listeners: {
enter: function(context) {
// Receives `enter` events for any labels of any dataset. Indices of the
// clicked label are: `context.datasetIndex` and `context.dataIndex`.
// For example, we can modify keep track of the hovered state and
// return `true` to update the label and re-render the chart.
context.hovered = true;
return true;
},
leave: function(context) {
// Receives `leave` events for any labels of any dataset.
context.hovered = false;
return true;
}
},
display: function(context) {
return context.active; // display labels with an odd index
},
font: {
size: '24px'
},
padding: '6',
align: 'end',
anchor: 'end',
borderRadius: 4,
backgroundColor: function(context) {
return context.active ? context.dataset.hoverBackgroundColor : context.dataset.backgroundColor;
},
borderColor: function(context) {
return context.dataset.borderColor;
},
borderWidth: 1,
color: 'rgb(253, 225, 186)',
textShadowBlur: 4,
textShadowColor: 'rgb(0, 0, 0)',
formatter: Math.round
}
}
}
});
if (stat) {
console.log(stat);
$('#activate').click(function() {
if (stat.getActiveElements().length > 0) {
stat.setActiveElements([]);
} else {
stat.setActiveElements([{
datasetIndex: 0,
index: 2,
}]);
//stat.$datalabels._hovered = true;
stat.$datalabels._datasets[0][1]._el.$context.active = true;
stat.$datalabels._datasets[0][1].$context.active = true;
stat.$datalabels._labels[1].$context.active = true;
stat.$datalabels._labels[1]._el.active = true;
stat.$datalabels._labels[1]._el.$context.active = true;
stat.$datalabels._datasets[0][1].update(stat.$datalabels._datasets[0][1].$context);
stat.$datalabels._labels[1].update(stat.$datalabels._labels[1].$context);
}
const tooltip = stat.tooltip;
if (tooltip.getActiveElements().length > 0) {
tooltip.setActiveElements([], {
x: 0,
y: 0
});
} else {
const chartArea = stat.chartArea;
tooltip.setActiveElements([{
datasetIndex: 0,
index: 2,
}], {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
}
stat.update();
});
}
Found a solution
I just modified the display function for datalabels integrating my external variable lastLabelH
var SCRIPTOBJ = null;
var LABEL = ["Gino", "Samantha", "Vercingetorige"];
var DATA = [5, 28, 500];
var MAX = Math.max(...DATA);
var ctx = $('#stat');
Chart.defaults.font.size = 14;
Chart.register(ChartDataLabels);
var lastLabelH = null;
var stat = new Chart(ctx, {
type: 'bar',
data: {
labels: LABEL,
datasets: [{
minBarLength: 15,
barPercentage: 1,
label: '# USERS',
data: DATA,
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(75, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
hoverBackgroundColor: [
'rgba(255, 99, 132, 1.0)',
'rgba(54, 162, 235, 1.0)',
'rgba(255, 206, 86, 1.0)',
'rgba(75, 192, 192, 1.0)',
'rgba(153, 102, 255, 1.0)',
'rgba(255, 159, 64, 1.0)'
],
borderWidth: 1
}]
},
plugins: [{
id: 'LabelHighlight',
beforeEvent(c, args, pluginOptions) {
const event = args.event;
/* if (event.type === 'mouseout') {
if (lastLabelH != null) {
//c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
c.update();
lastLabelH = null;
}
} else */
labelcolor(c);
}
}],
options: {
responsive: false,
interaction: {
mode: 'index',
intersect: true
},
/* onHover: function (event, elements, c) {
if (elements && elements.length) {
if (c._active.length > 0) {
let labelindex = c._active[0].index;
let label = c.scales.x._labelItems[labelindex];
label.color = "rgba(255, 255, 64, 1)";
lastLabelH = labelindex;
}
} else {
if (lastLabelH != null) {
c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
lastLabelH = null;
}
}
}, */
layout: {
padding: {
top: 50,
left: 0,
right: 0,
bottom: 0
}
},
indexAxis: 'x',
scales: {
x: {
beginAtZero: true,
ticks: {
display: true,
color: function(c) {
return lastLabelH != null && c.index == lastLabelH ? "rgba(255, 255, 64, 1)" : "rgba(255, 159, 64, 1)";
},
autoSkip: false,
maxRotation: 90,
minRotation: 90,
labelOffset: -8,
textStrokeColor: 'rgba(0, 0, 0, 0.5)',
textStrokeWidth: '2',
font: {
weight: 'bold',
family: 'Arial',
size: 16
},
align: 'start'
}
},
y: {
max: MAX + 1,
beginAtZero: true,
ticks: {
color: 'rgba(255, 159, 64, 1)',
stepSize: 1
}
}
},
plugins: {
legend: {
display: false
},
datalabels: {
listeners: {
enter: function(context) {
// Receives `enter` events for any labels of any dataset. Indices of the
// clicked label are: `context.datasetIndex` and `context.dataIndex`.
// For example, we can modify keep track of the hovered state and
// return `true` to update the label and re-render the chart.
context.hovered = true;
return true;
},
leave: function(context) {
// Receives `leave` events for any labels of any dataset.
context.hovered = false;
return true;
}
},
display: function(context) {
return lastLabelH != null && context.dataIndex == lastLabelH || context.active;
},
font: {
size: '24px'
},
padding: '6',
align: 'end',
anchor: 'end',
borderRadius: 4,
backgroundColor: function(context) {
return context.active ? context.dataset.hoverBackgroundColor : context.dataset.backgroundColor;
},
borderColor: function(context) {
return context.dataset.borderColor;
},
borderWidth: 1,
color: 'rgb(253, 225, 186)',
textShadowBlur: 4,
textShadowColor: 'rgb(0, 0, 0)',
formatter: Math.round
}
}
}
});
function labelcolor(c) {
if (c._active.length > 0) {
let labelindex = c._active[0].index;
if (c.scales.x._labelItems) {
let label = c.scales.x._labelItems[labelindex];
label.color = "rgba(255, 255, 64, 1)";
}
if (lastLabelH != null && lastLabelH != labelindex) {
if (c.scales.x._labelItems) {
c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
}
}
lastLabelH = labelindex;
} else {
if (lastLabelH != null) {
if (c.scales.x._labelItems) {
c.scales.x._labelItems[lastLabelH].color = "rgba(255, 159, 64, 1)";
}
lastLabelH = null;
c.update();
}
}
}
if (stat) {
$('#activate').click(function() {
if (stat.getActiveElements().length > 0) {
stat.setActiveElements([]);
} else {
stat.setActiveElements([{
datasetIndex: 0,
index: 2,
}]);
labelcolor(stat);
}
const tooltip = stat.tooltip;
if (tooltip.getActiveElements().length > 0) {
tooltip.setActiveElements([], {
x: 0,
y: 0
});
} else {
const chartArea = stat.chartArea;
tooltip.setActiveElements([{
datasetIndex: 0,
index: 2,
}], {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
}
stat.update();
});
}
body {
background-color: grey;
}
#stat {
margin-top: auto;
}
#content {
width: 300px;
margin: auto;
}
;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.min.js"></script>
<div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<div id="content">
<canvas id="stat" width="300" height="300" style="margin-top:10px"></canvas>
<input id="activate" type="button" value="Vergingetorige">
</div>
</div>
had to modify the color fuction to update when set null lastLabelH i also add color label from external trigger
updated jsfiddle
https://jsfiddle.net/netquik/e3jp2k5o/41/

Datepicker and chartjs in Laravel (old chart data when hover)

I have an issue when displaying a chart. I have a function that load data by default for today. After that, I can select a date range. But there is an issue when hovering on labels. They load old chart values and lines. I know that I need to use destroy or update function. But I don't know how to implement it in my code.
Script:
<script type="text/javascript">
$(document).ready(function() {
getdata_chart();
{{-- chartjs --}}
function getdata_chart(start_date='', end_date='')
{
$.ajax({
url: "{{ route('ajaxdata.getdata_chart') }}",
method: "GET",
data:{
start_date:start_date, end_date:end_date
},
success: function(data) {
console.log(data);
var timeFormat = 'DD MMM YYYY г. kk:mm:ss ч.';
var progress = document.getElementById('animationProgress');
var dateANDtime = [];
var Gblok9osx = [];
var Gblok9osy = [];
var Gblok11osx = [];
var Gblok11osy = [];
var Gfilblok10 = [];
var Gfilblok11 = [];
var Gcvn = [];
var Gndk = [];
var Gndk2 = [];
for (var i in data) {
dateANDtime.push(data[i].timestamp);
Gblok9osx.push(data[i].blok9osx);
Gblok9osy.push(data[i].blok9osy);
Gblok11osx.push(data[i].blok11osx);
Gblok11osy.push(data[i].blok11osy);
Gfilblok10.push(data[i].filblok10);
Gfilblok11.push(data[i].filblok11);
Gcvn.push(data[i].cvn);
Gndk.push(data[i].ndk);
Gndk2.push(data[i].ndk2);
}
var chartdata = {
labels: dateANDtime,
datasets: [{
fill: false,
label: 'Отвес блок 9 x',
backgroundColor: 'rgba(199, 228, 238, 0.75)',
borderColor: 'rgba(1, 150, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 0.75)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok9osx,
hidden: false
},
{
fill: false,
label: 'Отвес блок 9 y',
backgroundColor: 'rgba(163, 147, 222, 0.75)',
borderColor: 'rgba(50, 10, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok9osy,
hidden: true
},
{
fill: false,
label: 'Отвес блок 11 x',
backgroundColor: 'rgba(221, 221, 241, 0.75)',
borderColor: 'rgba(100, 100, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok11osx,
hidden: true
},
{
fill: false,
label: 'Отвес блок 11 y',
backgroundColor: 'rgba(147, 227, 227, 0.75)',
borderColor: 'rgba(1, 200, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok11osy,
hidden: true
},
{
fill: false,
label: 'Филтрация блок 10',
backgroundColor: 'rgba(139, 105, 132, 0.75)',
borderColor: 'rgba(255, 1, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gfilblok10,
hidden: true
},
{
fill: false,
label: 'Филтрация блок 11',
backgroundColor: 'rgba(0, 200, 1, 1)',
borderColor: 'rgba(0, 101,1, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gfilblok11,
hidden: true
},
{
fill: false,
label: 'КВН',
backgroundColor: 'rgba(30, 100, 100, 1)',
borderColor: 'rgba(100, 200,1, 0.75)',
hoverBackgroundColor: 'rgba(101, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gcvn,
hidden: true
},
{
fill: false,
label: 'КДК',
backgroundColor: 'rgba(30, 100, 100, 1)',
borderColor: 'rgba(100, 200,1, 0.75)',
hoverBackgroundColor: 'rgba(101, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gndk,
hidden: true
},
{
fill: false,
label: 'НДК',
backgroundColor: 'rgba(30, 100, 100, 1)',
borderColor: 'rgba(100, 200,1, 0.75)',
hoverBackgroundColor: 'rgba(101, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gndk2,
hidden: true
}
]
};
$('#reset_zoom').click(function() {
barGraph.resetZoom();
})
$("#save-btn").click(function() {
$("#mycanvas").get(0).toBlob(function(blob) {
saveAs(blob, "chart_1.png");
});
});
var config = {
type: 'line',
data: chartdata,
options: {
responsive: true,
title: {
display: true,
text: 'Диаграма: Отвеси и филтрации'
},
scales: {
yAxes: [{
type: type,
scaleLabel: {
display: true,
labelString: '[ mm ] ,[ m ], [ l/s ]'
},
ticks: {
beginAtZero: false
}
}],
xAxes: [{
type: 'time',
time: {
tooltipFormat: timeFormat,
displayFormats: {
'hour': timeFormat
}
},
scaleLabel: {
display: true,
labelString: 'Дата/Час'
},
ticks: {
beginAtZero: true
}
}]
},
// Container for pan options
pan: {
// Boolean to enable panning
enabled: true,
// Panning directions. Remove the appropriate direction to disable
// Eg. 'y' would only allow panning in the y direction
mode: 'y'
},
// Container for zoom options
zoom: {
// Boolean to enable zooming
enabled: true,
// Zooming directions. Remove the appropriate direction to disable
// Eg. 'y' would only allow zooming in the y direction
mode: 'xy'
},
animation: {
duration: 2000,
onProgress: function(animation) {
progress.value = animation.currentStep / animation.numSteps;
},
onComplete: function() {
window.setTimeout(function() {
progress.value = 0;
}, 2000);
}
},
legend: {
display: true,
labels: {
//fontColor: 'rgb(255, 99, 132)'
usePointStyle: true
}
}
},
plugins: [{
beforeDraw: function(c) {
var reset_zoom = document.getElementById("reset_zoom"); //reset button
var ticks = c.scales['x-axis-0', 'y-axis-0'].ticks.length; //x-axis ticks array
var labels = c.data.labels.length; //labels array
if (ticks < labels) reset_zoom.hidden = false;
else reset_zoom.hidden = true;
}
}]
};
var type = 'linear';
var ctx = document.getElementById("mycanvas");
var barGraph = new Chart(ctx, config);
window.onload = function() {
var ctx = document.getElementById("mycanvas");
window.myLine = barGraph;
};
document.getElementById('toggleScale').addEventListener('click', function() {
type = type === 'linear' ? 'logarithmic' : 'linear';
window.myLine.options.title.text = 'Диаграма('+type+'): Отвеси и филтрации';
window.myLine.options.scales.yAxes[0] = {
display: true,
type: type
};
window.myLine.update();
}); //end data
},
error: function(data) {
console.log(data);
}
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date != '')
{
getdata_chart(start_date, end_date);
}
else
{
alert('Both Date is required');
}
});
});
</script>
in to the controller:
function getdata_chart(Request $request)
{
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
$dateScope = array($start_date, $end_date);
};
$students = otv_fil::whereBetween('timestamp', $dateScope)
->selectRaw('timestamp,blok9osx,blok9osy,blok11osx,blok11osy,filblok10,filblok11,cvn,ndk,ndk - ? as ndk2',[743.38])
->orderBy('timestamp', 'ASC')
->get();
return response()->json($students);
}
The main part need to be in search click function right?

How to show percentage (%) in chart js

I want to show a percentage sign in the chart.I take data from my database from controller and show the data from vue js file.Here is my chart code.
<script>
import { Doughnut } from 'vue-chartjs';
export default {
props:['appurl'],
extends: Doughnut,
data(){
return{
item:[],
}
},
mounted() {
this.getData();
},
methods:{
setChartLoader: function(e) {
this.$emit('setChartLoader', e);
},
renderDoughnutChart(serviceName,serviceData){
this.renderChart({
datasets: [{
data: serviceData,
backgroundColor: [
'rgba(41, 121, 255, 1)',
'rgba(38, 198, 218, 1)',
'rgba(138, 178, 248, 1)',
'rgba(255, 100, 200, 1)',
'rgba(116, 96, 238, 1)',
'rgba(215, 119, 74, 1)',
'rgba(173, 92, 210, 1)',
'rgba(255, 159, 64, 1)',
'rgba(247, 247, 247, 1)',
'rgba(227, 247, 227, 1)',
],
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: serviceName,
}, {responsive: true, maintainAspectRatio: false, cutoutPercentage: 80})
},
getData(){
axios.get(this.appurl+'/dashboardgetdatadoughnut').then(response => {
this.item = response.data;
this.setChartLoader(false);
this.renderDoughnutChart(this.item.serviceName,this.item.serviceCount)
}).then(function(){
});
}
},
}
</script>
Here is my controller
public function doughnutData()
{
$serviceNameArray = array();
$serviceConfirmed = DB::table('bookings')->whereDate('booking_date', date('Y-m-d'))
->select('status',DB::raw('round(count(*) *100 / (select count(*) from bookings WHERE booking_date = curdate())) as count'))
->groupBy('status')->get();
$serviceCount = array();
foreach($serviceConfirmed as $name)
{
array_push($serviceNameArray,$name->status);
array_push($serviceCount,$name->count);
}
return ['serviceName'=>$serviceNameArray,
'serviceCount'=>$serviceCount];
}
I want to show 67% in the chart but i can not show the % sign
in the chart options, you can use the tooltips callback to customize the tooltip.
here, the % sign is added to the standard tooltip text...
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data['labels'][tooltipItem['index']] + ': ' + data['datasets'][0]['data'][tooltipItem['index']] + '%';
}
}
}
see following working snippet...
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['confirmed', 'pending'],
datasets: [{
data: [67, 33],
backgroundColor: [
'rgba(41, 121, 255, 1)',
'rgba(38, 198, 218, 1)',
'rgba(138, 178, 248, 1)',
'rgba(255, 100, 200, 1)',
'rgba(116, 96, 238, 1)',
'rgba(215, 119, 74, 1)',
'rgba(173, 92, 210, 1)',
'rgba(255, 159, 64, 1)',
'rgba(247, 247, 247, 1)',
'rgba(227, 247, 227, 1)',
],
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
cutoutPercentage: 80,
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data['labels'][tooltipItem['index']] + ': ' + data['datasets'][0]['data'][tooltipItem['index']] + '%';
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

Vuejs + Chartjs not showing chart

I’m having problem displaying the chart, Although the data in the getGender() is right, the chart is not displayed. If I get data outside axios it return no data even though I have set it in response.
<div class="x_content">
<canvas id="myChart"></canvas>
</div>
<script>
export default{
props: ['initialCounter'],
data(){
return{
gender:{},
}
},
mounted(){
axios.get('get-gender')
.then((response)=>{
this.getGender(response.data[0])
})
},
methods:{
getGender(data){
console.log(this.gender)
var ctx = document.getElementById("myChart")
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Male", "Female"],
datasets: [{
label: '# of Votes',
data: [data.male,data.female],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
});
}
}
}
</script>

Resources