take an array of objects and put it in a bar graph - javascript

i am a new when it comes to jquery and javascript but I'm trying learn slowly.What my question is, if i have a json file that looks like
var data= [{"tasknumber":304030,
"date":"2012-05-05",
"operator":"john doe"},
{"tasknumber":23130,
"date":"2012-07-07",
"operator":"john doeeeeeeee"},
{"tasknumber":233330,
"date":"2012-08-08",
"operator":"john doe"}]
and i applied .countBy to it from the underscore library to get a array that looks like this
{"john doe":2,"john doeeeeeeee":1}
so for the next part im using a sample jquery graph outline which i found online
<!DOCTYPE HTML>
<html>
<head>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
I tried a couple ways to call my new array within this part of the code
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
//insert here
]
}
]
but i only get blank screens and undefine when i try and open it.does anyone have any guidance for me on how to call my array within the datapoints?
my data is in a different file called task.json and i gotta call it using
var input=require('./task.json');
const _ = require(`underscore`);
var names=_.countBy(input,'operator');

Lets say, your JSON object is stored in some variable(eg: myObject).
var myObject = {"john doe":2,"john doeeeeeeee":1};
Declare a variable to store dataPoints from your JSON and push dataPoints into your array.
var dps = [];
for(var element in myObject) {
dps.push({label: element, y: myObject[element]});
}
Once you have done this, assign this variable (dps) to dataPoints of CanvasJS chart.
data: [
type: "column",
dataPoints: dps
]
You can see a working example in this fiddle.

Related

Counting string to plot a graph using chart.js and angular

I am trying to create a bar chart in angular using chart.js and angular.
I want to display the disaters vs area. with the type of disaster ( earthquake, hurricane, storm...etc) on the x-axis and area (as in location) on the y-axis.
However, the area data is string and does not work when trying to plot a bar graph as it requires numbers.
I am reading the data as follows:
ngOnInit(): void {
this.chartService.noOfEqu().subscribe((res) => {
let area = res.map((res) => res.area);
let disaster = res.map((res) => res.disasterNature);
new Chart('disasterCanvas', {
type: 'bar',
data: {
labels: disaster,
datasets: [
{
data: area,
label: 'area',
backgroundColor: '#A121D5',
},
],
},
options: {
plugins: {
legend: {
display: true,
},
},
scales: {
x: {
ticks: {
display: true,
},
},
y: {
ticks: {
display: true,
},
},
},
},
});
});
}
}
Where let area = res.map((res) => res.area); is the area variable.
I want to know what is the best way to structure the data to be entered into the graph.
The disaster data that is logged is:
and the area data :
How can i structure the area such that it counts how much areas that a disaster has occured and plot it on the bar chart?
Thank you in advance...if there is anything i can clarify please let me know in the comments
Also is there another way to display this data besides tallying the string data?
You need to add a labels array to the scale and set the type to category to use string data:
const options = {
type: 'bar',
data: {
labels: ["Earthquake", "Tornade", "Flood"],
datasets: [{
label: '# of Votes',
data: ['Paris', 'Berlin', 'London'],
backgroundColor: 'pink'
}]
},
options: {
scales: {
y: {
type: 'category',
reverse: true,
labels: ['', 'London', 'Paris', 'Berlin']
}
}
}
}
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>

Trying to access controller in JavaScript

My ultimate goal is to use information from my database to create a line graph using my MVC application. So far I have managed to gather this data using a view model and LINQ queries in my controller and I have made sure the data is accurate by running a test in the view. However, I'm having a hard time figuring out how to include it in my JavaScript file. In my controller I have a function
private DataBase db = new DataBase();
public ActionResult GetInfo() {
var model = new UserViewModel();
model.val1=db.table.Where(n=>n.UserID==curUser).Select(n=>n.SomeData).ToArray();
model.val2=db.table.Where(n=>n.UserID==curUser).Select(n=>n.MoreData).ToArray();
model.dictionary = the stuff from above;
And then in my JavaScript file I'm using Chart.Js to graph a chart. So far it just has fake data to make sure everything was linked up correctly but it looks like this:
jQuery(document).ready(function() {
var chart=new CanvasJS.Chart("moodgraph",{
animationEnabled: false,
theme: "light2",
title: {
text: "Simple Line Chart"
},
axisY: {
includeZero: false
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: [
{ x: 1,y: 450 },
{ y: 414 },
{ y: 520,indexLabel: "\u2191 highest",markerColor: "red",markerType: "triangle" },
{ y: 460 },
{ y: 450 },
{ y: 500 },
{ y: 480 },
{ y: 480 },
{ y: 410,indexLabel: "\u2193 lowest",markerColor: "DarkSlateGrey",markerType: "cross" },
{ y: 500 },
{ y: 480 },
{ y: 510 }
]
}]
});
chart.render();
});
That graph does appear in my view so I know all that is working fine. What I've been struggling with is figuring out how to get that dataPoints to populate with the dictionary values that I grabbed in my controller... So far I tried using
var model=#Model.Dictionary
to access the information but that threw an error. And then I've struggled with trying to return an object in the controller but that messes with code that I can't touch as someone else wrote it for this project. I know I'm missing one simple piece but my Google searches don't show me how to do this in the strict parameters I'm stuck with in this project.
How do I access the view model data in my separate JavaScript file?
you can use this :
1 - In your controller :
*
*
ViewBag.Dico = model.dictionary;
return View("chartPage");
2 - in your chartPage.cshtml (or declare your variable globally 'Layout.cshtml'):
<script>
var myPoints= #Html.Raw(Json.Encode(ViewBag.Dico));
</script>
3 - in ChartJs:
jQuery(document).ready(function() {
var chart=new CanvasJS.Chart("moodgraph",{
*
*
*
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: (typeof(myPoints) != "undefined" ? myPoints: [])
}]
});
chart.render();
});
using Chart.JS library you can make dynamic charts from the database data by following the next steps
Model:
suppose you have model for graph data as following:
public class JsResultChart
{
public string Name { get; set; }
public double Value { get; set; }
}
Controller:
return your data from the controller (using model, viewbag..etc) as list
var JsResultChart= new List<JsResultChart>
{
new JsResultChart{ Name ="first", Value = 100 }, //data will be fetched from db
new JsResultChart{ Name ="second", Value = 200 },
};
Model.JsResultChart = JsResultChart;
View:
add something like this:
<div class="row">
<div class="col-md-12">
<input type="hidden" id="Lables" name="Lables" value="#Json.Encode(Model.ChartData.Select(x => x.Name).ToList())" />
<input type="hidden" id="Values" name="Values" value="#Json.Encode(Model.ChartData.Select(x => x.Value).ToList())">
<canvas id="myChart" style="margin: 0 auto;" class="NotPrintable"></canvas>
<div id="ResultsDiv"></div>
</div>
</div>
javascript:
var Names = $("#Lavels").val();
var Numbers = $("#Values").val();
Names = JSON.parse(Names);
Numbers = JSON.parse(Numbers);
var data = {
labels: Names,
datasets: [{
fill: false,
data: Numbers,
label: "Value" //you can write(label: Names) rather than (label: "Value")
}]
};
var ctx = $("#myChart");
var barChart = new Chart(ctx, {
type: 'line',
data: data,
options: options //add your options
});

Chart.js dinamically populate data in Oracle Application Express

Hi I am suing the library chart.js 2.7 with Oracle application express and I am facing issue with passing data array.
I set up same variable fields to store the the array for the chart, but the chart is not displayed/rendered.
note: P79_.. are item of the page (text field) containing the array from ad hoc queries.
Any suggestions? thanks in advance
here's my code
<script>
var BUDGET1 =[document.getElementById("P79_BUDGET1_AC").value]
var BUDGET2 =[document.getElementById("P79_BUDGET2_AC").value]
var ACTUAL1 =[document.getElementById("P79_ACTUAL1_AC").value]
var ACTUAL2 =[document.getElementById("P79_ACTUAL2_AC").value]
new Chart(document.getElementById("mixed-chart"), {
type: 'bar',
data: {
labels: ["P01", "P02", "P03", "P04","P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12"],
datasets: [{
label: "Plan1",
type: "line",
borderColor: "#c45850",
data: BUDGET1,
fill: false
}, {
label: "Plan2",
type: "line",
borderColor: "#3e95cd",
data: BUDGET2,
fill: false
}, {
label: "Actual1",
type: "bar",
backgroundColor: "#ffbb99",
backgroundColorHover: "#ff9933",
data: ACTUAL1,
}, {
label: "Actual2",
type: "bar",
backgroundColor: "#99ffbb",
backgroundColorHover: "#00ff40",
data: ACTUAL2
}
]
},
options: {
title: {
display: true,
text: 'Plan Trend'
},
tooltips: {
callbacks: {
// this callback is used to create the tooltip label
label: function(tooltipItem, data) {
// get the data label and data value to display
// convert the data value to local string so it uses a comma seperated number
var dataLabel = data.labels[tooltipItem.index];
var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
// make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
if (Chart.helpers.isArray(dataLabel)) {
// show value on first line of multiline label
// need to clone because we are changing the value
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
// return the text to display on the tooltip
return dataLabel;
}
}
},
legend: { display: true}
}
});
</script>
I do not know if these instructions to create these arrays works. Could try to use console.log in these values to check if works?
var BUDGET1 =[document.getElementById("P79_BUDGET1_AC").value]
var BUDGET2 =[document.getElementById("P79_BUDGET2_AC").value]
console.log(BUDGET1);
console.log(BUDGET2);
var ACTUAL1 =[document.getElementById("P79_ACTUAL1_AC").value]
var ACTUAL2 =[document.getElementById("P79_ACTUAL2_AC").value]
console.log(ACTUAL1);
console.log(ACTUAL2);
*You can execute this code on console. On chrome press F12, go to console.
Look at this post to see how convert a string with commas to array. Convert string with commas to array

JSON Data formatting for Highcharts

I have a json object as shown below. I would like it to groupBy based on a specific property say "SEX" and pass it to highcharts such that I have only one xAxis category for "TIME" and chart should look like below:
[{"TIME":"2017-09-15","SEX":"MALE","ARIZONA":483280000.0,"IDAHO":6624960.0,"RATE":98.6291686272},
{"TIME":"2017-09-15","SEX":"FEMALE","ARIZONA":1034350000.0,"IDAHO":32409500.0,"RATE":96.8666697274},
{"TIME":"2017-09-16","SEX":"MALE","ARIZONA":482379000.0,"IDAHO":9578100.0,"RATE":98.0144001036},
{"TIME":"2017-09-16","SEX":"FEMALE","ARIZONA":1052960000.0,"IDAHO":40686800.0,"RATE":96.1359744871},
{"TIME":"2017-09-17","SEX":"FEMALE","ARIZONA":1052530000.0,"IDAHO":41476900.0,"RATE":96.0593301937},
{"TIME":"2017-09-17","SEX":"MALE","ARIZONA":1052590000.0,"IDAHO":41479900.0,"RATE":96.0893301937},]
How do we achieve it for the above JSON format..??
First of all, you should use filter method in order to obtain two arrays: one for male and another for female entities.
Then use map method in order to obtain dates, femaleRates and maleRates arrays.
let array=[{"TIME":"2017-09-15","SEX":"MALE","ARIZONA":483280000.0,"IDAHO":6624960.0,"RATE":98.6291686272}, {"TIME":"2017-09-15","SEX":"FEMALE","ARIZONA":1034350000.0,"IDAHO":32409500.0,"RATE":96.8666697274}, {"TIME":"2017-09-16","SEX":"MALE","ARIZONA":482379000.0,"IDAHO":9578100.0,"RATE":98.0144001036}, {"TIME":"2017-09-16","SEX":"FEMALE","ARIZONA":1052960000.0,"IDAHO":40686800.0,"RATE":96.1359744871}, {"TIME":"2017-09-17","SEX":"FEMALE","ARIZONA":1052530000.0,"IDAHO":41476900.0,"RATE":96.0593301937}, {"TIME":"2017-09-17","SEX":"MALE","ARIZONA":1052590000.0,"IDAHO":41479900.0,"RATE":96.0893301937}];
let males=array.filter(a=>a.SEX=='MALE');
let females=array.filter(a=>a.SEX=='FEMALE');
let dates=males.map(a=>a.TIME);
let malesRates=males.map(a=>a.RATE);
let femaleRates=females.map(a=>a.RATE);
console.log(dates);
console.log(malesRates);
console.log(femaleRates);
The last step is to display data in your chart.
let array=[{"TIME":"2017-09-15","SEX":"MALE","ARIZONA":483280000.0,"IDAHO":6624960.0,"RATE":98.6291686272}, {"TIME":"2017-09-15","SEX":"FEMALE","ARIZONA":1034350000.0,"IDAHO":32409500.0,"RATE":96.8666697274}, {"TIME":"2017-09-16","SEX":"MALE","ARIZONA":482379000.0,"IDAHO":9578100.0,"RATE":98.0144001036}, {"TIME":"2017-09-16","SEX":"FEMALE","ARIZONA":1052960000.0,"IDAHO":40686800.0,"RATE":96.1359744871}, {"TIME":"2017-09-17","SEX":"FEMALE","ARIZONA":1052530000.0,"IDAHO":41476900.0,"RATE":96.0593301937}, {"TIME":"2017-09-17","SEX":"MALE","ARIZONA":1052590000.0,"IDAHO":41479900.0,"RATE":96.0893301937}];
let males=array.filter(a=>a.SEX=='MALE');
let females=array.filter(a=>a.SEX=='FEMALE');
let dates=males.map(a=>a.TIME);
let malesRates=males.map(a=>a.RATE);
let femaleRates=females.map(a=>a.RATE);
Highcharts.chart('container', {
xAxis: {
categories:dates
},
series: [{
name: 'Males',
data: malesRates
}, {
name: 'Females',
data:femaleRates
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>

Templates and Javascript

So, I'm trying to implement CanvasJS into my project. I'm having a hard time trying to get the values from my structs to work in the tags. It works fine for the HTML code, but I'm not sure how to get it work for the javascript. Is it a different syntax?
<html>
<head>
<title>results</title>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
/*dataPoints: [
{ label: "Time", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]*/
dataPoints: [
{{range .Pair}}
{label: {{.Time}}, y: {{.Value}}}
{{end}}
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<h1>{{.Id}}</h1>
<ol>
{{range .Pair}}
<ul>
<li>Time: {{.Time}}</li>
<li>Value: {{.Value}}</li>
</ul>
{{end}}
</ol>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>

Categories

Resources