in this code, I was able to get the data from database in the JSON format. now iam struggling to draw a chart in JS with columns as values and rows as time stamp. i have a controller(chartController) that goes into the database and extract the desired data and change it into JSON format, that is values and timestamp. then i created a route for this controller, Route::get('json/{notification_id}','ChartController#speedHistory')->name('speedhistory')
i hava a js class as follows,
document.addEventListener('DOMContentLoaded', function() {
$.getJSON("json", function getdata(data) {
console.log(data);
var pageSpeedValues = o_response;
createChartHistory(pageSpeedLabels);
});
function fetchValues(Labels, Values) {
var pageSpeedLabels = Values;
var pageSpeedValues = Labels;
createChartHistory(pageSpeedLabels);
}
// This function allows us to create a chart for the history page
function createChartHistory(pageSpeedLabels, pageSpeedValues) {
var ctx = document.getElementById("pageSpeedHistoryChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: pageSpeedLabels,
datasets: [{
label: 'PageSpeed History',
data: pageSpeedValues,
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)',
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(32, 206, 86, 0.5)',
'rgba(77, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)'
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
max: 100,
min: 0
}
}]
}
}
});
}
if(document.querySelector('#pageSpeedHistoryChart')) {
getdata();
}
});
I am not getting the data from the controller into the app.js class, any one how get the idea? iam learning js but seems a bit difficult at this point.
here is my chart controller
<?php
namespace App\Http\Controllers;
use App\Notification;
use App\Status;
use Illuminate\Http\Request;
class ChartController extends Controller
{
public function speedHistory($notification_id){
$o_notification = Notification::find(intval($notification_id));
$o_status = Status::where('name','speed')->first();
$o_response = $o_notification->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get()
->transform(function ($item, $key) {
return collect([
'values' => $item->pivot->values,
'created_at' => $item->pivot->created_at->toDateTimeString()
]);
});
return response()->json($o_response);
}
}
Related
I'm trying to export the excel data and want to show chart according to that data but chart is not visible. When I use mock data chart is working fine but not when I'm exporting the data. Issue is with the date. data = [['2023-02-01', '2023-02-03'],
['2023-02-03', '2023-02-06'],
['2023-02-06', '2023-02-09']]
when I'm using above date as mock, it is working fine but when I use same format date through excel its not working.
export class BarGraphComponent {
public chart: any;
workBook: any = null;
labels: any = [];
data: any = [];
constructor() {}
ngOnInit() {
}
onFileChange(ev: any) {
let jsonData = null;
const reader = new FileReader();
const file = ev.target.files[0];
reader.onload = (event) => {
const data = reader.result;
this.workBook = XLSX.read(data, { type: 'binary'});
jsonData = this.workBook.SheetNames.reduce((initial: any, name: any) => {
const sheet = this.workBook.Sheets[name];
initial[name] = XLSX.utils.sheet_to_json(sheet, {raw: false});
return initial;
}, {});
for(let i = 0; i<jsonData.Sheet1.length; i++){
this.data.push([jsonData.Sheet1[i].Start, jsonData.Sheet1[i].Finish]);
this.labels.push(jsonData.Sheet1[i].Activity)
}
}
reader.readAsBinaryString(file);
this.createChart();
}
createChart(){
console.log(this.data);
this.chart = new Chart("MyChart", {
type: 'bar', //this denotes tha type of chart
data: {// values on X-Axis
labels: this.labels,
datasets: [{
label: 'PS-6 Data in Graph Format',
data: this.data,
backgroundColor: [
'rgba(255, 26, 104, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255, 26, 104, 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)',
'rgba(0, 0, 0, 1)',
],
borderWidth: 1
}]
},
options: {
indexAxis:'y',
scales: {
x: {
min: '2023-02-01',
type: 'time',
time: {,
unit: 'day',
}
}
}
}
});
}
}
This is my callback function and i have getData(data); to get all JSON data ,
And created dataset = [ ]; (for get some specific properties from my all JSON data)
function call_some_api(getData){
request('https://someUrl..........',{json:true},(err,res,data) => {
if (err) {
console.log(err);
}
if (res.statusCode === 200){
var dataset = [];
data.forEach((value, key)=>{
dataset.push(value.close);
});
getData(data);
}
});
};
And use callback and pass my all JSON data in res.render it works normally.
But i want add dataset variable from my callback into res.render to page know variable dataset
app.get('/chart',function(req,res){
call_some_api(function(getAPI_data){
res.render('chart',{
dataChart: getAPI_data,
});
});
});
I just need to my /chart page (handlebars template) know my variable from callback function. (for build chart)
This my /chart (handlebars template)
<canvas id="myChart" width="400" height="400"></canvas>
<br><br>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
// I just want add in this line below.
data: dataset,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
stacked: true
}
}
}
});
</script>
This error
You mean like a second argument, analog to getAPI_data ?
function call_some_api(getData){
request('https://someUrl..........',{json:true},(err,res,data) => {
if (err) {
console.log(err);
}
if (res.statusCode === 200){
var dataset = [];
// BTW this can be better/cleaner done with `.map` ;)
data.forEach((value, key)=>{
dataset.push(value.close);
});
getData(data, dataset);
}
});
};
And in your render/http endpoint
app.get('/chart',function(req,res){
call_some_api(function(getAPI_data, dataset){
res.render('chart',{
dataChart: getAPI_data,
dataset
});
});
});
NOTE: Code not tested, inline edited.
im stuck with a code.
on my mvc application, i had a view, the view contains a dropdownlist, and a bar chart from charts.js nugget. the datasources of the chart are the model.field1, and model.field2 for each axis,
so, im trying, to, when i change dropdownlist item my model change , im passing the dropdownlist.val() to
an action in the controller, that action change the model, the model returns chaged to the view and the chart must change dinamicly, i post my code, dont know what i doing wrong, but dont work. debuggin i find that the value of the dropdown is passing to the action, but i dont know why the chart dont change.
my view
#model GestorBd.Models.FuenteDatos
<br /><br />
<div>
#Html.DropDownList("TiposAFT", null, "--Opciones--", htmlAttributes: new { #class = "form-control", #onchange = "CargarPartial()" })
</div>
<div style="width:800px; height: 1600px; ">
<canvas id="myChart" ></canvas>
</div>
#section Scripts{
<script>
function CargarPartial() {
var desc = $('#TiposAFT').val();
$.ajax({
url: '/Estadisticas/Index',
type: "POST",
data: JSON.stringify({ param: desc }),
contentType: 'application/json',
success: function (data) {
}
});
}
</script>
<script src="~/Scripts/Chart.js"></script>
<script>
var arregloarea = #Html.Raw(System.Web.Helpers.Json.Encode(Model.Area.ToArray()));
var arregloCantidad = #Html.Raw(System.Web.Helpers.Json.Encode(Model.Cantidad.ToArray()));
var label = #Html.Raw(System.Web.Helpers.Json.Encode(Model.label));
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: arregloarea,
datasets: [{
label: label,
data: arregloCantidad,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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)'
],
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
}
my action
public ActionResult Index(string param)
{
FuenteDatos nuevo = new FuenteDatos();
if(string.IsNullOrEmpty(param))
{ param = "Computadora"; }
nuevo = nuevo.ObjetenerDatosDescripcion(param);
Listados a = new Listados();
ViewBag.TiposAFT = a.TiposAFT();
return View(nuevo);
}
I'm working with chartjs and trying to update my initial state with an API call which looks like:
this.state = {
data: {
labels: [], //<-- SET THIS STATE
datasets: [{
fill: 'false',
lineTension: 0,
label: 'Price in USD',
data: [], //<-- SET THIS STATE
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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)'
],
borderWidth: 1
}]
}
}
I need to setState for labels - which I have done already. But got lost and confused as to also setState for code below at the same time.
data: {
labels: [],
datasets: [{
fill: 'false',
lineTension: 0,
label: 'Price in USD',
data: [], <------THISSSS
Here's what I did to set my labels state
let labels = this.state.data.labels
labels = timeData
this.setState(({data}) => ({data: {
...data,
labels: labels
}}))
You are initializing labels as this.state.data.labels, which is fine, but then you change it to timeData, which I'm assuming is declared somewhere else in the code. You don't need to set labels to this.state.data.labels if you're going to assign it a new value immediately after. Also, if you want to simplify it further, you can also exclude the line labels = timeData and just use timeData in the setState call.
As for the this.setState() call, you should not be passing it a function.
To answer your question, this is how you can set the state of labels and the second data property without affecting the rest of the state:
this.setState({
data: {
labels: timeData,
datasets: [{
...this.state.data.datasets,
data: SOME_VALUE_HERE
}]
}
});
I'm newbie in Angular and I want to show charts with dynamic data.
I'm trying with Chart.js I've made the import and examples works.
So basically the system recieves from PHP JSON data and I show the data.
`<div *ngFor="let i of idspreguntas; let f = index">
<canvas id="{{i}}"></canvas>
<span *ngIf="f == max2-1" id="inservible">
{{loadGraphics()}}
</span>
</div>`
But here is a problem the HTML code executes after I set the Chart properties and doesn't work.
My solution was check the last position of Array (Previously transformed from JSON) and execute loadGraphics() I gave more time adding timeout per Chart.
loadGraphics() {
$('#inservible').remove();
let index = 0;
console.log(this.lista);
for (const i of this.lista) {
setTimeout(this.cargaChart(i, index), 2000);
index++;
}
}
I know this is a very bad practice but I don't know how to make it.
Finally here is the cargaChart function
cargaChart(i, u) {
const respu = [];
const cont = [];
if (i.Respuesta1 !== '') {
respu.push(i.Respuesta1);
cont.push(i.Contador1);
}
if (i.Respuesta2 !== '') {
respu.push(i.Respuesta2);
cont.push(i.Contador2);
}
if (i.Respuesta3 !== '') {
respu.push(i.Respuesta3);
cont.push(i.Contador3);
}
if (i.Respuesta4 !== '') {
respu.push(i.Respuesta4);
cont.push(i.Contador4);
}
if (i.Respuesta5 !== '') {
respu.push(i.Respuesta5);
cont.push(i.Contador5);
}
if (i.Pregunta !== '') {
const myChart = new Chart($('#' + i.idPregunta)[0].getContext('2d'), {
type: 'bar',
data: {
labels: respu,
datasets: [{
label: i.Pregunta,
data: cont,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
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)'
],
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
},
});
}
}
This is de unique method that is worked for me. (Almost)
The last dataof array doesn't work console said 'TypeError: Cannot read property 'getContext' of undefined'
But only in the last position, others positions works well.
Here the JSON
[{"idPregunta":"04QLDT5S","NumeroPregunta":"3","Nombre":"¿Quién eres?","Pregunta":"¿Quién eres?","Respuesta1":"Yo","Contador1":"0","Respuesta2":"Tú","Contador2":"1","Respuesta3":"Ella","Contador3":"0","Respuesta4":"","Contador4":0,"Respuesta5":"","Contador5":0},{"idPregunta":"0Z000BZ8","Pregunta":"Qué hace","Respuesta1":"Nada","Contador1":"0","Respuesta2":"Llorando","Contador2":"0","Respuesta3":"Triste","Contador3":"0","Respuesta4":"","Contador4":"0","Respuesta5":"","Contador5":"0"},{"idPregunta":"0Y2FG4XL","Pregunta":"¿Qué duces=","Respuesta1":"Nada","Contador1":"0","Respuesta2":"Algo","Contador2":"0","Respuesta3":"Simbólico","Contador3":"0","Respuesta4":"Majestuoso","Contador4":"0","Respuesta5":"Brilante","Contador5":"0"}]
Sorry for all.. I'm learning.