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)"
}]
}
});
Related
I am trying to draw a two-line chart with two datasets that share the same labels using chart.js on my ASP.NET MVC app.
I am only getting the data from "Value" plotted on the chart and not "Age" and I cannot find the reason why.
Relevant Controller code:
public ActionResult GetLineChartData()
{
List <LineChartData> dataForLineChart = new List <LineChartData> ();
dataForLineChart.Add(new LineChartData {
Date = DateTime.NOW, Value = 100, Age = 20
});
return Json(dataForLineChart, JsonRequestBehavior.AllowGet);
}
Relevant View code:
$.ajax({
type: "Post",
url: '#Url.Action("GetLineChartData", "Posts")',
contentType: false,
processData: false,
data: dataFromForm,
dataType: "json",
traditional: true,
success: function (data) {
console.log(data);
var labels = data.map(function (e) {
return e.Date;
});
var data = data.map(function (e) {
return e.Value;
});
var data2 = data.map(function (e) {
return e.Age;
});
var ctx = scatterChart.getContext('2d');
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Test"
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
},
{
label: "Test",
data: data2,
backgroundColor: 'rgba(242, 204, 143, 1)'
}
]
}
};
}
});
(Some code I do not consider important is hidden)
Issue & Concern
Because the below line overwrites the original data value.
var data = data.map(function (e) {
return e.Value;
});
After the above line, now the data array was overwritten as an array of integers instead of an array of objects. Based on your sample response from API, the current value of data will be: [100].
var data2 = data.map(function (e) {
return e.Age;
});
From the above line, it can't find the Age property in the element. Hence the result of data2 will be: [undefined].
This is why the data2 is not rendered in the chart.
Solution
Create another variable for the data transformation to avoid overwriting the existing data value.
var dataset = data.map(function (e) {
return e.Value;
});
var dataset2 = data.map(function (e) {
return e.Age;
});
var config = {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Test',
data: dataset,
backgroundColor: 'rgba(0, 119, 204, 0.3)',
},
{
label: 'Test',
data: dataset2,
backgroundColor: 'rgba(242, 204, 143, 1)',
},
],
},
};
Demo # StackBlitz
I am beginner on this Chart.js and wanna ask, How can I hide the labels and 0 values in the bar Chart. I cannot just hide the whole Dataset since I am using a SQL Table to get the Values "into" Chart.Js. I just want the bar chart show only if the labels have the value. Need your help
sample chart
{
{
$.post("datachartasr.php",
function (data)
{
console.log(data);
var intake = [];
var active = [];
var inactive = [];
var deffered = [];
var widthdrawn = [];
var dis_ter_dereg = [];
var missing = [];
for (var i in data) {
intake.push(data[i].intake);
active.push(data[i].active);
inactive.push(data[i].inactive);
deffered.push(data[i].deffered);
widthdrawn.push(data[i].widthdrawn);
dis_ter_dereg.push(data[i].dis_ter_dereg);
missing.push(data[i].missing);
}
var chartdata = {
labels: intake,
datasets: [
{
label: 'Active Status',
backgroundColor: '#1E90FF',
borderColor: '#1E90FF',
hoverBackgroundColor: '#1E90FF',
hoverBorderColor: '#666666',
data: active
},
{
label: 'Deferred Status',
backgroundColor: '#708090',
borderColor: '#708090',
hoverBackgroundColor: '#708090',
hoverBorderColor: '#666666',
data: deffered
},
.....
.....
.....
]
};
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
});
});
}
}
You can have the below function inside data labels to hide the Zero value:
options: {
plugins: {
datalabels: {
display: function(context) {
return context.dataset.data[context.dataIndex] !== 0; // or >= 1 or ...
}
}
}
}
See more on this issue here https://github.com/chartjs/chartjs-plugin-datalabels/issues/6
// here I am taking another json encoded data from phpfile
$(document).ready(function () {
showGraph();
});
function showGraph()
{
{
$.post("phpfile.php",
function (data)
{
console.log(data);
var name = [];
var marks = [];
var height=[];
//and here as I couldn't encode two json array's separetly I'm declaring it to a variable and then using it
var jsonfile =[{"height":"85","st_name":"Name1"},{"height":"100","st_name":"Name3"},{"height":"92","st_name":"Name4"},{"height":"104","st_name":"Name5"},{"height":"91","st_name":"Name2"},{"height":"99","st_name":"Name6"},{"height":"140","st_name":"AI346"},{"height":"139","st_name":"abc"},{"height":"141","st_name":"def"},{"height":"140","st_name":"ghi"},{"height":"144","st_name":"jkl"},{"height":"130","st_name":"lmn"},{"height":"142","st_name":"opq"},{"height":"132","st_name":"rst"},{"height":"135","st_name":"xyz"},{"height":"135","st_name":"asdfsf"}];
//here I am reading the data from phpfile(1st Json array)
for (var i in data) {
name.push(data[i].st_name);
marks.push(data[i].height);
}
//here i am trying to access data from second json
for (var i=0;i<jsonfile.length;i++){
if(jsonfile[i].height==100)
{ height.push(jsonfile[i].height)}
}
//my graph function ,when I do this I am getting a single point with second json(height variable) but I need to highlight the particular point under a condition... I am not understanding how to do it.
var chartdata = {
labels: name,
datasets: [
{
label: 'height',
fill:false,
lineTension:0.5,
backgroundColor: '#5B2C6F',
borderColor: '#5B2C6F',
pointHoverBackgroundColor: '#5B2C6F',
pointHoverBorderColor: '#5B2C6F',
data: marks
//data:height
},
{
label: 'weight',
fill:false,
lineTension:0.1,
backgroundColor: '#C0392B',
borderColor: '#C0392B',
pointHoverBackgroundColor: '#C0392B',
pointHoverBorderColor: '#C0392B',
data:height,
//data:height
}
]
};
var graphTarget = $("#graphCanvas");
var lineGraph = new Chart(graphTarget, {
type: 'line',
data: chartdata,
options :{
scales:{
xAxes: [{
display: false //this will remove all the x-axis grid lines
}]
}
}
});
});
}
}
</script>
i will try to improve this.
var data =[{"height":"85","st_name":"Name1","color":"rgba(85, 85, 255, 255)"},{"height":"100","st_name":"Name3","color":"rgba(255, 0, 0, 2)"},{"height":"92","st_name":"Name4","color":"rgba(85, 85, 255, 255)"},{"height":"104","st_name":"Name5","color":"rgba(85, 85, 255, 255)"}];
var height = [];
var label = [];
var color = [];
for(i = 0; i<data.length; i++){
height.push(data[i]['height']);
label.push(data[i]['st_name']);
color.push(data[i]['color']);
}
var ctx = document.getElementById('myLine').getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: label,
datasets: [{
data: height,
pointBorderColor: color,
}]
}
});
I'm trying to display a stock chart on the webpage when it is opened, but it won't display unless i press f12
I've already tried including the code inside a function and displaying the chart when a button is pressed but it also doesn't seem to work
<script type="text/javascript">
var highlist = [];
var lowlist = [];
var datelist = [];
$.getJSON("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=G9UIQ9K1TRVBHHME", function(json) {
var times = json["Time Series (Daily)"];
for(var time in times)
{
var stock_info = times[time];
var highItem = stock_info["2. high"];
var lowItem = stock_info["3. low"];
highlist.push(highItem);
lowlist.push(lowItem);
datelist.push(time);
}
});
var ctx = document.getElementById("lineChart").getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: datelist,
datasets: [{
label: "My First dataset",
label: "High",
backgroundColor: [
'rgba(204, 204, 255, .2)',
],
borderColor: [
'rgba(51, 51, 255, .7)',
],
borderWidth: 2,
data: highlist
},
{
label: "Low",
backgroundColor: [
'rgba(0, 137, 132, .2)',
],
borderColor: [
'rgba(0, 10, 130, .7)',
],
data: lowlist
}]
},
});
</script>
Expect the chart to show but nothing is displaying unless f12 is pressed
The getJson is an asynchronous function, so JS will send a request and then draw your chart before it gets a response.
Put all the chart stuff inside a function, and then call that function after the for loop inside your getJson callback.
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>