I use Charts.js in my Angular project (not AngularJS) and i want to use data from my database to make a graphic with woman / man, but i didn't know how create a loop and count number of woman or number of men :
First, for the Chart, my html code :
<canvas id="myChart" width="700" height="400"></canvas>
typescript :
ngAfterViewInit() {
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: ["Femme", "Homme"],
datasets: [{
label: '# of Votes',
data: [2,2],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
display:true
}
});
}
and the code to get my data :
javascript :
app.get("/api/getUser",function(req,res){
model.find({},function(err,data){
if(err){
res.send(err);
}
else{
res.send(data);
}
});
})
typescript :
GetUser(){
return this.http.get('http://localhost:8080/api/getUser/')
.map((response: Response) => response.json())
}
and the second typescript :
ngOnInit() {
this.newService.GetUser().subscribe(data => this.Repdata = data)
}
for finish, this is the collection :
{
"_id" : ObjectId("5b9551a60e89ad15a8ff77fb"),
"name" : "XXX",
"prenom" : "KEVIN",
"datenaissance" : "17/11/2011",
"mail" : "KEVIN#laposte.fr",
"tel" : "XXXXXXXXXX",
"sexe" : "Homme",
"adresse" : "XXXXXXXX",
"note" : [
{
"matiere" : "Français",
"note" : "10/20",
"date" : "01/09/2018"
},
{
"matiere" : "Anglais",
"note" : "07/20",
"date" : "26/09/2018"
},
{
"matiere" : "EPS",
"note" : "15/20",
"date" : "29/09/2018"
}
]
}
I want to count the number of sexe:Homme and sexe:Femme to use this for create my graphic but i didn't know how
thank you very much
If I do this my charts can't find the countHomme and countFemme :
javascript :
app.get("/api/getUser",function(req,res){
model.find({},function(err,data){
if(err){
res.send(err);
}
else{
res.send(data);
var countHomme = model.where({ 'sexe': 'Homme' }).count();
res.send(countHomme);
var countFemme = model.where({ 'sexe': 'Femme' }).count();
res.send(countFemme);
}
});
})
typescript :
ngAfterViewInit() {
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: ["Femme", "Homme"],
datasets: [{
label: '# of Votes',
data: [countFemme,countHomme],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
display:true
}
});
}
IMO, its better to ask the data about male and female sex from the backend through an API.
You can try to count the fields using mongoose ORM via Model.count() method and it can send back a JSON object with total counts as per your need and you can feed it directly to chart.js
Related
I'm doing a project which is to extract data from python and show it in jsp dashboard.
I'm trying to load a json file to chartjs but it's not giving result
<script>
$.getJSON("resources/json_test.json", function(data) {
var labels = data.department.map(function(e) {
return e[1];
});
var data = data.volunteer.map(function(e) {
return e[1];
});
var context = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(context, {
type : 'bar',
data : {
labels : labels,
datasets : [ {
label : 'volunteer',
lineTension : 0.1,
data : data,
backgroundColor : "rgba(255, 99, 132, 0.2)"
}]
}
});
});
{"department":{"0":"IT","1":"Math","2":"English","3":"Software","4":"Game"},"volunteer":{"0":409,"1":1781,"2":476,"3":550,"4":562}}
To call .map() the datastructure needs to be an array, and since yours are objects it aint working, if you change your code to this it should work:
const labels = Object.values(data.department)
const parsedData = Object.values(data.volunteer)
const context = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(context, {
type: 'bar',
data: {
labels: labels,
datasets: [ {
label: 'volunteer',
lineTension: 0.1,
data: parsedData,
backgroundColor: "rgba(255, 99, 132, 0.2)"
}]
}
});
I have a template that, among other things, displays a current market price through a placeholder, i.e., {{ market.current_price }}, and an accompanying price graph using ChartJS, rendered in the template in a canvas tag, <canvas id="myChart"></canvas>.
My question: since the market price changes as different users engage with the underlying market, is there a straightforward way to periodically (say, every 10 seconds) refresh the placeholder and chart in the template, to make sure each user is looking at the most recent price/graph?
I'm trying to avoid having to refresh the entire page, if at all possible.
If it makes any difference, the chart is rendered through Ajax, as follows:
{% block jquery %}
var endpoint = "{% url 'chart_data' market.id %}"
var defaultData = []
var labels = []
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
defaultData = data.prices
price_array_length = defaultData.length + 1
labels = data.price_dates
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets : [{
label: 'Market price',
data: defaultData,
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1
}
}]
},
animation: {
duration: 500 // general animation time
},
hover: {
animationDuration: 500 // duration of animations when hovering an item
},
responsiveAnimationDuration: 500 // animation duration after a resize
}
})
}
})
{% endblock %}
Many thanks in advance for any advice!
Here's one solution: Building on #MichaelCacciano's suggestion, I wrapped the JQuery in a function (refresh_graph), and also dropped the Django placeholder in favour of a tag (currentPrice), both of which now update every second, as follows:
<script>
function refresh_graph() {
{% block jquery %}
var endpoint = "{% url 'chart_data' market.id %}"
var defaultData = []
var labels = []
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
defaultData = data.prices
price_array_length = defaultData.length + 1
labels = data.price_dates
var current = defaultData[defaultData.length-1];
document.getElementById('currentPrice').innerHTML = current;
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets : [{
label: 'Market price',
data: defaultData,
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1
}
}]
},
animation: {
duration: 0 // general animation time
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 500 // animation duration after a resize
}
})
}
})
setTimeout(refresh_graph, 1000);
}
setTimeout(refresh_graph, 0);
{% endblock %}
</script>
Putting data from a database into an array in chart.js is not working and gives an empty doughnut:
i'm using angular / spring boot for back end
constructor(private statistiqueService:StatistiqueService) {
this.statistiqueService.getStateClient().subscribe(
resp=>{
for(var i=0;i<resp.length;i++){
this.dataStatus[i]=resp[i][1];
this.labelStatus[i]=resp[i][0];
}
}
);
}
statusClient(){
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: this.dataStatus,
backgroundColor: [
'rgba(255, 99, 132, 0.8)',
'rgba(54, 162, 235, 0.8)'
]
}],
labels:this.labelStatus
}
});
}
ngOnInit() {
console.log("Data");
console.log(this.dataStatus);
console.log("Label");
console.log(this.labelStatus);
this.statusClient();
}
My data after log is here
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
I want to create dynamic graphics directly linked to a PostgreSQL DB.
For the moment, I succeeded on bar diagrams, but it is complicated on other types of diagram including the radar.
My goal is to get an IRIS (iri_code), a profile on 3 relative variables (txact, txchom, pop_txevol) as in the image below
what I want
First of all, here is my PHP (data_radar.php)
<?php
$dbconn = pg_connect("host='' dbname='' user='' password=''")
or die('Erreur de connexion'.pg_last_error());
$query = "SELECT iri_code, iri_pop_txevol, iri_txact, iri_txchom FROM demo_geo.demo_iris_view WHERE iri_code = '352380801'";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$array = array();
while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$array[] = $row;
}
$data=json_encode($array);
echo $data;
pg_free_result($result);
pg_close($dbconn);
?>
It works, here is the json output
[{"iri_code":"352380801","iri_pop_txevol":"3.1","iri_txact":"69.5","iri_txchom":"9.8"}]
But I don't understand how to set the graphic on the JS part. Is the structure of the json good?
$(document).ready(function() {
$.ajax({
url : "http://localhost/test_a/data_radar.php",
type : "GET",
dataType: 'json',
success : function(data){
console.log(data);
var irisA = [];
var txact = [];
var txchom = [];
var txevol = [];
for(var i in data) {
irisA.push(data[i].iri_code);
txact.push(data[i].iri_txact);
txchom.push(data[i].iri_txchom);
txevol.push(data[i].iri_pop_txevol);
}
var ctx1 = $("#canvas-radar");
var data1 = {
labels : [txact, txchom, txevol],
datasets : [
{
label : "IRIS",
data : irisA,
backgroundColor: "rgba(179,181,198,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBackgroundColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(179,181,198,1)"
}
]
};
var options = {
title : {
display : true,
position : "top",
text : "Radar test",
fontSize : 14,
fontColor : "#111"
},
legend : {
display : true,
position : "bottom"
}
};
var chart1 = new Chart( ctx1, {
type : "radar",
data : data1,
options : options
});
},
error : function(data) {
console.log(data);
}
});
});
Here is what it gives
radar chart bug
I have searched forums but I confess that I am not yet comfortable, if someone can enlighten me to accelerate my learning it would be very very nice
Thank you in advance and good day !
Here's how you could accomplish that ...
let json = [{ "iri_code": "352380801", "iri_pop_txevol": "3.1", "iri_txact": "69.5", "iri_txchom": "9.8" }, { "iri_code": "352380703", "iri_pop_txevol": "23.0", "iri_txact": "15.3", "iri_txchom": "29.8" }];
let label = [];
let data = [];
// generate label and data dynamically
json.forEach(e => {
label.push(e.iri_code);
data.push([+e.iri_pop_txevol, +e.iri_txact, +e.iri_txchom]);
});
let ctx = document.querySelector('#canvas').getContext('2d');
let chart = new Chart(ctx, {
type: 'radar',
data: {
labels: ['txevol', 'txact', 'txchom'],
datasets: [{
label: label[0],
data: data[0],
backgroundColor: 'rgba(0,119,204,0.2)',
borderColor: 'rgba(0,119,204, 0.5)',
borderWidth: 1,
pointBackgroundColor: 'rgba(0, 0, 0, 0.5)'
}, {
label: label[1],
data: data[1],
backgroundColor: 'rgba(255, 0, 0 ,0.15)',
borderColor: 'rgba(255, 0, 0 ,0.45)',
borderWidth: 1,
pointBackgroundColor: 'rgba(0, 0, 0, 0.5)'
}]
},
options: {
title: {
display: true,
position: "top",
text: "Radar test",
fontSize: 14,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom"
},
scale: {
pointLabels: {
fontSize: 11
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>