Regrouping data chartjs - javascript

I need your help to solve my problem with regrouping data, I'm trying to create a chart using chartjs with dynamic data from an xml link, the code shown below works but not the exact way I want to.
In my current situation, I get "for example" ChefProjet=10, ChefProjet=7, ChefProjet=7, ChefProjet=7, so ChefProjet is repeated four times but I want to get ChefProjet shown only one time and it equals 31 (10+7+7+7), you can see the chart in the link of the picture. ↓
https://scontent.ftun11-1.fna.fbcdn.net/v/t1.15752-9/67271937_905246276477408_4457126943061442560_n.png?_nc_cat=101&_nc_oc=AQnTcvx_xBHwZTvX8evyZbi7zACL6uBR10or9Onqp5MJ-6yQLM9oa9eE0Bg2mkBsLhc&_nc_ht=scontent.ftun11-1.fna&oh=866978b6e1752f6dcf9be0086eba0122&oe=5DB50932
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + add2,
method: "GET",
headers: { "Accept": "application/json; odata=nometadata" },
success: function (data) {
if (data.value.length > 0) {
var pieValues = [];
var pieLabels = [];
for (var i = 0; i < data.value.length; i++) {
pieValues.push(parseInt(data.value[i].AssignmentWork));
pieLabels.push(data.value[i].ResourceName);
}
var pieData = {
datasets: [{
borderColor: "#80b6f4",
pointBorderColor: "#80b6f4",
pointBackgroundColor: "#80b6f4",
pointHoverBackgroundColor: "#80b6f4",
pointHoverBorderColor: "#80b6f4",
pointBorderWidth: 1,
pointHoverRadius: 1,
pointHoverBorderWidth: 1,
pointRadius: 2,
fill: false,
borderWidth: 1,
data: pieValues
}],
labels: pieLabels
};
var ctx = document.getElementById("myChart");
if (window.myPieChart2 != undefined)
{
window.myPieChart2.destroy();
}
//
window.myPieChart2 = new Chart(ctx, {
type: 'line',
data: pieData,
options: {
responsive: true,
legend: { display: false },
title: {
display: true,
text: 'Pourcentage d\'achevement des phases'
},
scales: {
xAxes: [{
gridLines: {
zeroLineColor: "transparent"
},
ticks: {
maxRotation: 90,
minRotation: 90,
fontSize:10
}
}],
yAxes: [{
ticks: {
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 5,
padding: 20
},
gridLines: {
drawTicks: false,
display: false
}
}]
}
}
});
}
},
error: function (data) {
}
});
I will appreciate your time.

It worked, here is the solution:
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + add2,
method: "GET",
headers: { "Accept": "application/json; odata=nometadata" },
success: function (data) {
if (data.value.length > 0) {
var reducedObject = {};
for (var i = 0; i < data.value.length; i++) {
if (!reducedObject[data.value[i].ResourceName]) {
reducedObject[data.value[i].ResourceName] = 0;
}
reducedObject[data.value[i].ResourceName] += parseInt(data.value[i].AssignmentWork);
}
var keys = Object.keys(reducedObject);
var pieLabels = [];
var pieValues = [];
for (var i = 0; i < keys.length; i++) {
pieValues.push(reducedObject[keys[i]]);
pieLabels.push(keys[i]);
}
var pieData = {
datasets: [{
borderColor: "#80b6f4",
pointBorderColor: "#80b6f4",
pointBackgroundColor: "#80b6f4",
pointHoverBackgroundColor: "#80b6f4",
pointHoverBorderColor: "#80b6f4",
pointBorderWidth: 1,
pointHoverRadius: 1,
pointHoverBorderWidth: 1,
pointRadius: 2,
fill: false,
borderWidth: 1,
data: pieValues
}],
labels: pieLabels
};
var ctx = document.getElementById("myChart");
if (window.myPieChart2 != undefined)
{
window.myPieChart2.destroy();
}
//
window.myPieChart2 = new Chart(ctx, {
type: 'line',
data: pieData,
options: {
responsive: true,
legend: { display: false },
title: {
display: true,
text: 'Pourcentage d\'achevement des phases'
},
scales: {
xAxes: [{
gridLines: {
zeroLineColor: "transparent"
},
ticks: {
maxRotation: 90,
minRotation: 90,
fontSize:10
}
}],
yAxes: [{
ticks: {
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 5,
padding: 20
},
gridLines: {
drawTicks: false,
display: false
}
}]
}
}
});
}
},
error: function (data) {
}
});

Related

Chart.js remove label from legend for if dataset values

I have a chart with multiple datasets. I want the label of a dataset from the legend to not be visible if all the values in a dataset are null. I've found some solutions but they were only working if data was declared in the initial configuration. In my case it is dynamically updated.
Here is the code:
self.initGraph = function () {
ctxWell = document.getElementById("wellChart").getContext('2d');
if (wellChart != undefined)
wellChart.destroy();
wellChart = new Chart(ctxWell, {
type: 'line',
data: {
labels: [],
datasets: [
{
backgroundColor: reportColor.Green,
borderColor: reportColor.Green,
label: 'Motor Frequency Hz',
yAxisID: 'y-axis-2',
data: [],
borderWidth: 1,
pointRadius: 0,
fill: false
},
{
backgroundColor: reportColor.Turquoise,
borderColor: reportColor.Turquoise,
label: 'Pump Discharge Pressure ' + helpers.getListSelectedValue(self.dischargePressureID(), self.pressureList()),
yAxisID: 'y-axis-1',
data: [],
borderWidth: 1,
pointRadius: 0,
fill: false
}
,
]
},
options: {
maintainAspectRatio: false,
animation: {
duration: 0
},
scales: {
yAxes: [
{
id: 'y-axis-1',
// stacked: true,
scaleLabel: {
display: true,
fontSize: 18,
labelString: helpers.getListSelectedValue(self.intakePressureID(), self.pressureList())
},
ticks: {
beginAtZero: true
}
},
{
id: 'y-axis-2',
position: 'right',
display: self.checkAxis(),
scaleLabel: {
display: self.checkAxis(),
fontSize: 18,
labelString: "Hz, " + helpers.getListSelectedValue(self.motorTemperatureID(), self.temperatureList())
},
ticks: {
beginAtZero: true
}
}
]
},
elements: {
line: {
tension: 0.000001
}
},
legend: {
display: true,
onClick: wellChartLegendClick,
}
},
}
});
wellChart.update();
};
self.updateWellDaily = function () {
var chart = wellChart;
chart.data.labels = [];
for (var j = 0; j < chart.data.datasets.length; j++) {
chart.data.datasets[j].data = [];
}
for (var i = 0; i < self.wellResults().length; i++) {
chart.data.labels.push(self.wellResults()[i].reportedTime);
chart.data.datasets[0].data.push(self.wellResults()[i].motorFrequency);
chart.data.datasets[1].data.push(self.wellResults()[i].pumpDischargePressure);
}
chart.update();
};
self.initGraph();
self.updateWellDaily();
The legend filter function can be used for this, if you tell it to hide labels where in the dataset all data is zeros it will update dynamicly, see example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 0],
borderWidth: 1,
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
},
{
label: '# of Counts',
data: [1, 2, 3,4,5,2],
borderWidth: 1,
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}
]
},
options: {
plugins: {
legend: {
labels: {
filter: (legendItem, chartData) => (!chartData.datasets[legendItem.datasetIndex].data.every(item => item === 0))
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("tt").addEventListener("click", () => {
chart.data.datasets[1].data = [0, 0, 0, 0, 0, 0];
chart.update()
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<button id="tt">
change data
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>

How to plot a bar chart using chart.js and Ajax in C#

I am trying to display a bar chart using chart.js and C# code with an Ajax call in my application using the below script and code. The chart is not displaying. The code is in C# and I am writing the UI code in aspx file.
$(document).ready(function () {
var jsonData = JSON.stringify({
});
$.ajax({
type: "POST",
url: "Home.asmx/GetMonthtlyInspectionData",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.d.Datas;
var label = response.d.Labels;
let ctx = $("#barChart").get(0).getContext("2d");
ctx.height = 130;
new Chart(ctx, {
type: 'bar',
data: {
labels: label,
type: 'bar',
defaultFontFamily: 'Montserrat',
datasets: [{
data: data,
label: "Approved Request",
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'transparent',
borderWidth: 2,
pointStyle: 'circle',
pointRadius: 5,
pointBorderColor: '#847DFA',
pointBackgroundColor: '#fff',
}]
},
options: {
responsive: !0,
maintainAspectRatio: true,
tooltips: {
mode: 'index',
titleFontSize: 12,
titleFontColor: '#fff',
bodyFontColor: '#fff',
backgroundColor: '#000',
titleFontFamily: 'Montserrat',
bodyFontFamily: 'Montserrat',
cornerRadius: 3,
intersect: false,
},
legend: {
display: true,
position: 'top',
labels: {
usePointStyle: true,
fontFamily: 'Montserrat',
},
},
scales: {
xAxes: [{
beginAtZero: true,
display: true,
gridLines: {
display: false,
drawBorder: true
},
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
beginAtZero: true,
gridLines: {
display: false,
drawBorder: true
},
scaleLabel: {
display: true,
labelString: 'Inspection Request Count'
}
}]
},
title: {
display: true,
}
}
});
}
});
});
Below is my aspx.cs code -
public List<HomeModel> GetMonthtlyCaseData()
{
List<HomeModel> t = new List<HomeModel>();
string conn = ConfigurationManager.ConnectionStrings["ConnCase"].ConnectionString;
using (OracleConnection cn = new OracleConnection(conn))
{
string myQuery = "Select count(CaseNo),to_char(to_date(CaseDt, 'DD-MM-YYYY'),'Month') from t_case_detail group by CaseNo,CaseDt ";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = myQuery;
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cn.Open();
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
int counter = 0;
while (dr.Read())
{
HomeModel tsData = new HomeModel();
tsData.month = dr["CaseDt"].ToString();
tsData.requestNo = dr["CaseNo"].ToString();
t.Add(tsData);
counter++;
}
}
}
return t;
}

How do remove the bottom scale on a Chart.js bar chart

I'm using Chart.js to create the following chart:
The issue is that I want to make the scale at the bottom only show 0 and the maximum number (here being 12).
JavaScript:
<script>
new Chart(document.getElementById("leads-bar"), {
type: 'horizontalBar',
data: {
labels: ["Hot", "Warm", "Cold"],
datasets: [
{
backgroundColor: ["#d23232", "#ff9347", "#bbbbbb"],
data: [7, 9, 11]
}
]
},
options: {
legend: {
display: false
},
tooltips: {
display: false
},
title: {
display: false
},
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false,
drawBorder: false,
},
scaleShowLabels: false,
}],
yAxes: [{
stacked: false,
gridLines: {
color: ["#eeeeee"]
}
}]
}
}
});
var dataArr = [154.23, 203.21, 429.01, 637.41];
var chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: [154.23, 203.21, 429.01, 637.41],
datasets: [{
label: 'LINE',
data: dataArr,
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)',
fill: false,
tension: 0
}]
},
options: {
scales: {
xAxes: [{
ticks: {
min: Math.min.apply(this, dataArr),
max: Math.max.apply(this, dataArr),
callback: function(value, index, values) {
if (index === values.length - 1) return Math.min.apply(this, dataArr);
else if (index === 0) return Math.max.apply(this, dataArr);
else return '';
}
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

How to show/hide animation when legend clicked chart js

i add animation to show label value data on value points in line chart js. but when i click the legend to hide a line, the label not disappear. to be honest, i really don't have any clue to fix it.
the chart now
the chart after hide some line with legend
var ctxTotal = $("#grap_trajec_divisi");
var chartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'bottom',
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function (tooltipItems, data) {
var dataM = tooltipItems.yLabel;
formatM(dataM);
var multistringText = [data_M];
multistringText.push(tooltipItems.yLabel);
multistringText.push(data.datasets[tooltipItems.datasetIndex].label);
return multistringText;
}
}
},
scales: {
xAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: true,
},
scaleLabel: {
display: false,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: true,
},
scaleLabel: {
display: false,
labelString: 'Value'
},
ticks: {
callback: function (value, index, values) {
var dataYaxis = value;
formatM(dataYaxis);
return data_M;
}
},
}]
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = '.7rem "Calibri",sans-serif';
ctx.fillStyle = '#555';
ctx.textAlign = "center";
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
formatM(data);
ctx.fillText(data_M, bar._model.x, bar._model.y - 5);
});
});
}
}
//title: {
// display: true,
// text: 'Chart.js Line Chart - proyeksi'
//}
};
var chartData = {
labels: arr,
datasets: [{
label: "RKAP",
data: value_LT,
fill: false,
borderColor: "rgb(89,159,240)",
pointBorderColor: "rgb(89,159,240)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}, {
label: "Target",
data: value_LT2,
fill: false,
borderColor: "rgb(186,179,61)",
pointBorderColor: "rgb(186,179,61)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}, {
label: "Actual",
data: value_LO,
fill: false,
borderColor: "rgb(78,199,138)",
pointBorderColor: "rgb(78,199,138)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}, {
label: "Proyeksi",
data: value_LP,
fill: false,
borderColor: "rgb(241,151,89)",
pointBorderColor: "rgb(241,151,89)",
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 1,
pointHoverBorderWidth: 1,
pointRadius: 3,
spanGaps: true,
}],
};
var config = {
type: 'line',
options: chartOptions,
data: chartData
};
if (window.chartTrajecDivisi != undefined) {
window.chartTrajecDivisi.destroy();
}
window.chartTrajecDivisi = new Chart(ctxTotal, config);
i want to hide the label when line hide by clicking the label, so the label and the line is hide / show together.
I think this works.
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
formatM(data);
ctx.fillText(data_M, bar._model.x, bar._model.y - 5);
});
}
});
i found the answer for this. just remove the animation, and used plugin datalabel chart js.

Mark X value on Chart Js graph

I have this chart:
And I want to mark a given X value for the user. For example I want something like this:
The chart code:
var chart = new Chart(document.getElementById("featureChart"), {
type: 'scatter',
data: {
datasets: [{
label: "Benign_Cross_Entropy",
data: customize_date
}]
},
options: {
responsive: true
}
});
How can I do it ? Thanks
Edit: I'm trying to use annotation and i'm not sure what is wrong.
The example beaver gave in the comments looks good
var ann = [1];
var ann_values = ["your data"];
var annotations_array = ann.map(function(date, index) {
return {
type: 'line',
id: 'vline' + index,
mode: 'vertical',
scaleID: 'x-axis-0',
value: date,
borderColor: 'green',
borderWidth: 1,
label: {
enabled: true,
position: "center",
content: ann_values[index]
}
}
});
var chart = new Chart(document.getElementById("featureChart"), {
type: 'scatter',
data: {
datasets: [{
label: "Benign_Cross_Entropy",
data: customize_date,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderJoinStyle: 'miter'
// pointBorderColor: "rgba(75,192,192,1)",
// pointBackgroundColor: "#fff"
}
]
},
options: {
responsive: true,
elements: { point: { radius: 0 } },
annotation: {
drawTime: 'afterDatasetsDraw',
annotations: annotations_array,
}
}
});
Here is the correct usage of annotation plugin:
var ann = [1];
var ann_labels = ["your data"];
var annotations_array = ann.map(function(value, index) {
return {
type: 'line',
id: 'vline' + index,
mode: 'vertical',
scaleID: 'x-axis-0',
value: value,
borderColor: 'red',
borderWidth: 2,
label: {
enabled: true,
position: "center",
content: ann_labels[index]
}
}
});
console.log(annotations_array)
var data = [{
x: 0,
y: 5
}, {
x: 1,
y: 6
}, {
x: 2,
y: 8
}, {
x: 3,
y: 9
}];
var chart = new Chart(document.getElementById("ctx"), {
type: 'scatter',
data: {
datasets: [{
label: "Benign_Cross_Entropy",
data: data,
borderWidth: 2,
showLine: true,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
//borderCapStyle: 'butt',
//borderJoinStyle: 'miter'
// pointBorderColor: "rgba(75,192,192,1)",
// pointBackgroundColor: "#fff"
}]
},
options: {
responsive: true,
//elements: { point: { radius: 0 } },
annotation: {
drawTime: 'afterDatasetsDraw',
annotations: annotations_array,
},
scales: {
xAxes: [{
type: 'linear',
id: 'x-axis-0',
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.5/chartjs-plugin-annotation.min.js"></script>
<canvas id="ctx"></canvas>
Here is a jsfiddle as well: https://jsfiddle.net/beaver71/e3b1Ldms/

Categories

Resources