get json data from my controller in highcharts.js - javascript

I am trying to make a highchart which should show me number of reserved rooms for every type:
Here is my controller with GetHighChart method:
public JsonResult GetHighChart()
{
var viewModel = Reservation.RoomTypeByDate(5);
var result = new JsonResult { Data = viewModel};
return result;
}
Reservetion.RoomTypeByDate looks like this:
public static List<dynamic> RoomTypeByDate(int? LunaDorita)
{
var result=DBContext.Current.ExecuteProcedure("RoomtypeCountbydate",
new QueryParam<int>("#p_ID", LunaDorita.Value)).Map();
return result;
And here is my stored procedure:
SELECT Room_Type, COUNT(*) AS NumarRezervari
FROM dbo.Reservation re
JOIN dbo.Room ro ON ro.RoomID = re.Room_ID
JOIN dbo.Room_Type rt ON rt.RoomType_ID = ro.Room_Type_ID
WHERE MONTH(re.Data_Check_in)=#p_ID
GROUP BY Room_Type
My Json Result is:
[[{"Key":"Room_Type","Value":"Double"},{"Key":"NumarRezervari","Value":2}], [{"Key":"Room_Type","Value":"LUXURY"},{"Key":"NumarRezervari","Value":1}],[{"Key":"Room_Type","Value":"Triple"},{"Key":"NumarRezervari","Value":1}]]
How should I modify this javascript file so that instead of the series from below to have my data from my GetHighChart method from myReports controler.So instead of name i want to have my RoomType for example Double and instead of data to have my own data [2,5....]?
$(function () {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Monthly Average Temperature'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Temperature (°C)'
}
},
tooltip: {
enabled: false,
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '°C';
}
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
});
});
});

If you are using Visual Studio you can use DotNet.Highcharts to make building highchart objects much easier. By doing so you can work with Series and Data objects directly and then just pass them into Highcharts. It takes the creation of the JavaScript out of the picture. Below is a sample of how I create my charts in MVC 3. As you can see I am using LINQ to SQL to gather the required data for the chart. I am creating a list of Series to hold the data. This is done dynamically so I can add as many Series as needed for the chart without having to know how many there will be beforehand. Then I create the chart and pass the list of Series to it.
public ActionResult CombinerBarToday(DateTime? utcStartingDate = null,
DateTime? utcEndingDate = null)
{
//GET THE GENERATED POWER READINGS FOR THE SPECIFIED DATETIME
var firstQ = from s in db.PowerCombinerHistorys
join u in db.PowerCombiners on s.combiner_id equals u.id
where s.recordTime >= utcStartingDate
where s.recordTime <= utcEndingDate
select new
{
CombinerID = u.name,
Current = s.current,
RecordTime = s.recordTime,
Voltage = s.voltage,
Watts = (s.current * s.voltage)
};
//GET A LIST OF THE COMBINERS CONTAINED IN THE QUERY
var secondQ = (from s in firstQ
select new
{
Combiner = s.CombinerID
}).Distinct();
/* THIS LIST OF SERIES WILL BE USED TO DYNAMICALLY ADD AS MANY SERIES
* TO THE HIGHCHARTS AS NEEDED WITHOUT HAVING TO CREATE EACH SERIES INDIVIUALY */
List<Series> allSeries = new List<Series>();
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
//LOOP THROUGH EACH COMBINER AND CREATE SERIES
foreach (var distinctCombiner in secondQ)
{
var combinerDetail = from s in db2.PowerCombinerHistorys
join u in db2.PowerCombiners on s.combiner_id equals u.id
where u.name == distinctCombiner.Combiner
where s.recordTime >= utcStartingDate
where s.recordTime <= utcEndingDate
select new
{
CombinerID = u.name,
Current = s.current,
RecordTime = s.recordTime,
Voltage = s.voltage,
Watts = (s.current * s.voltage) / 1000d
};
var results = new List<object[]>();
foreach (var detailCombiner in combinerDetail)
{
results.Add(new object[] {
TimeZoneInfo.ConvertTimeFromUtc(detailCombiner.RecordTime, easternZone),
detailCombiner.Watts });
}
allSeries.Add(new Series
{
Name = distinctCombiner.Combiner,
//Data = new Data(myData)
Data = new Data(results.ToArray())
});
}
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Spline, ZoomType = ZoomTypes.X})
.SetTitle(new Title { Text = "Combiner History" })
.SetSubtitle(new Subtitle { Text = "Click and drag in the plot area to zoom in" })
.SetOptions(new GlobalOptions { Global = new Global { UseUTC = false } })
.SetPlotOptions(new PlotOptions
{
Spline = new PlotOptionsSpline
{
LineWidth = 2,
States = new PlotOptionsSplineStates { Hover = new PlotOptionsSplineStatesHover { LineWidth = 3 } },
Marker = new PlotOptionsSplineMarker
{
Enabled = false,
States = new PlotOptionsSplineMarkerStates
{
Hover = new PlotOptionsSplineMarkerStatesHover
{
Enabled = true,
Radius = 5,
LineWidth = 1
}
}
}
}
})
.SetXAxis(new XAxis
{
Type = AxisTypes.Datetime,
Labels = new XAxisLabels
{
Rotation = -45,
Align = HorizontalAligns.Right,
Style = "font: 'normal 10px Verdana, sans-serif'"
},
Title = new XAxisTitle { Text = "Time(Hour)" },
})
.SetYAxis(new YAxis
{
Title = new YAxisTitle { Text = "Kilowatt" }
})
.SetSeries(allSeries.Select(s => new Series {Name = s.Name, Data = s.Data }).ToArray());
return PartialView(chart);
}

Follow the following steps:
Make chart a global variable
var chart;
You can define load event to your chart like this
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: requestData
}
}
}
here requestData is a javascript function. In this function you can bind data dynamically to the chart.
function requestData() {
var pointArray = [];
for (var i = 0; i < data2.length; i++) {
// var series, shift;
// var point = new Array(new Date(data2[i].UTC).getTime(), parseFloat(data2[i].Value));
var point = {
x: new Date(data2[i].UTC).getTime(),
y: parseFloat(data2[i].Value)
};
chartRTM.series[0].addPoint(point);
}
chartRTM.series[0].redraw();}
NOTE: Here data2 is a json list of the data to be bound.

Related

How to call ASP.NET jQuery Ajax function from CodeFile Method ["website Project"]

I'm calling the ajax function using javascript in website project and the webmethod aspx page is running on CodeFile="NewPLPage.aspx.cs" and when I run the NewPLPage.aspx page I'm getting the following error
Error is :
Uncaught TypeError: Cannot read properties of undefined (reading '0')
Screenshot
website project example pic
Screenshot
I'm not sure where I did the mistake in the code
this my aspx code "NewPLPage.aspx" :
<figure class="highcharts-figure">
<div id="container"></div>
</figure>
javascript code :
$(document).ready(function () {
linedata();
}
function linedata() {
//var param = "Line";
var param = { Terms: $('#portperfgrphtab6M').text() };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(param),
url: "NewPLPage.aspx/GetLineChartData",
dataType: "json",
success: function (Result) {
Result = Result.d;
var data = [];
for (var i in Result) {
//var serie = new Array(Result[i].Names, Result[i].Values, Result[i].Dummy);
var serie = new Array(Result[i].Date, Result[i].Niftyperform, Result[i].Portfolioperform);
data.push(serie);
}
DreawLineChart(data);
$(".highcharts-credits")[0].innerHTML = "";
$(".highcharts-button-symbol").hide();
},
error: function (Result) {
alert("Something Went Wrong !");
}
});
}
/*Inter link of "linedata()"*/
function DreawLineChart(series) {
Highcharts.chart('container', {
chart: {
type: 'line'
},
title: {
text: 'Performance Graph'
},
//subtitle: {
// text: 'Source: WorldClimate.com'
//},
xAxis: {
//categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
// 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
categories: [series[0][0], series[1][0], series[2][0], series[3][0], series[4][0], series[5][0]] // Getting error : Uncaught TypeError: Cannot read properties of undefined (reading '0')
},
yAxis: {
title: {
text: ''
},
//labels: {
// formatter: function () {
// return this.value + '°';
// }
//}
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
line: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1,
}
}
},
series: [{
name: 'NiftyPerform',
marker: {
symbol: 'diamond'
},
//data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, {
// y: 26.5,
// marker: {
// symbol: 'url(https://www.highcharts.com/samples/graphics/sun.png)'
// }
//}, 23.3, 18.3, 13.9, 9.6]
data: [series[0][1], series[1][1], series[2][1], series[3][1], series[4][1], series[5][1]]
}, {
name: 'PortfolioPerform',
marker: {
symbol: 'diamond'
},
//data: [{
// y: 3.9,
// marker: {
// symbol: 'url(https://www.highcharts.com/samples/graphics/snow.png)'
// }
//}, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
data: [series[0][2], series[1][2], series[2][2], series[3][2], series[4][2], series[5][2]]
}]
});
}
this is NewPlPage.cs page code :
[WebMethod]
public static List<Performgraph> GetLineChartData(string Terms)
{
//string Terms
//string Terms = "";
DataTable dt = new DataTable(); //null;
//List<object> chartData = new List<object>();
//List<string> reports = new List<string>();
List<string> starttime = new List<string>();
List<Performgraph> performgraphs = new List<Performgraph>();
GetPerformgraphapp getPerformgraphapp = GraphData(); // Getting service data without any error
if (Terms == "6M")
dt = getPerformgraphapp.M6.ConvertToDataSet("Graph6M").Tables[0];
else if (Terms == "1Y")
dt = getPerformgraphapp.YR1.ConvertToDataSet("Graph1Y").Tables[0];
else if (Terms == "2Y")
dt = getPerformgraphapp.YR2.ConvertToDataSet("Graph2Y").Tables[0];
else if (Terms == "3Y")
dt = getPerformgraphapp.YR3.ConvertToDataSet("Graph3Y").Tables[0];
else if (Terms == "5Y")
dt = getPerformgraphapp.YR5.ConvertToDataSet("Graph5Y").Tables[0];
if (dt.Rows.Count > 0 && dt != null)
{
////Insert Label for columns in First position.
//reports.Insert(0, "LineChart");
//reports.Add("NiftyPerform");
//reports.Add("PortfolioPerform");
////Add the columns Array to the Chart Array.
//chartData.Add(reports.ToArray());
starttime = (from p in dt.AsEnumerable()
select p.Field<string>("DATE")).ToList();
string yyMMM = "";
foreach (string datetime in starttime)
{
List<object> niftyperform = (from p in dt.AsEnumerable()
where p.Field<string>("DATE") == datetime
select p.Field<double>("niftyperform")).Cast<object>().ToList();
//Should not use or convert the string data
//List<object> totals = (from p in dt.AsEnumerable()
// where p.Field<string>("DATE") == datetime
// select Convert.ToString(p.Field<double>("portfolioperform"))).Cast<object>().ToList();
List<object> portfolioperform = (from p in dt.AsEnumerable()
where p.Field<string>("DATE") == datetime
select p.Field<double>("portfolioperform")).Cast<object>().ToList();
yyMMM = Convert.ToDateTime(datetime).ToString("yyMMM");
//string[] yymmm = Convert.ToDateTime(datetime).GetDateTimeFormats();
//totals.Insert(0, Convert.ToDouble(niftyperform[0]));
//totals.Insert(0, yyMMM.ToUpper().ToString());
//chartData.Add(portfolioperform.ToArray());
performgraphs.Add(new Performgraph
{
Date = yyMMM.ToUpper().ToString(),
Niftyperform = Convert.ToDouble(niftyperform[0]),
Portfolioperform = Convert.ToDouble(portfolioperform[0])
});
}
//return chartData;
}
else
{
//Page page = (Page)HttpContext.Current.Handler;
//Control myDiv = (Control)page.FindControl("pfperformchart");
}
return performgraphs;
}
Class :
public class Performgraph
{
public string Date { get; set; }
public double Niftyperform { get; set; }
public double Portfolioperform { get; set; }
}
Give the best suggestion to resolve this error
I'm new to ajax call and webmethod concepts.

Unable to pass Json data into ajax success call in asp.net mvc

i have made an application in mvc dot net using highcharts
i have connected them to DB and showed them in view
till now every thing is running fine
but now i want to do is that if DB is updated the charts will be automatically show the updated data. for now i have to refresh the page to view updated data and it's showing well but all i want is not refresh it.
i have searched many articles and found than ajax polling should help me out so in my controller code i have passed all data in ViewData coming from reader
while (reader.Read())
{
energy_kwh.Add(Convert.ToDouble(reader["Energy_kWh"]));
power_kw.Add(Convert.ToDouble(reader["Power_kW"]));
voltage_1.Add(Convert.ToDouble(reader["Voltage_Phase_1"]));
voltage_2.Add(Convert.ToDouble(reader["Voltage_Phase_2"]));
voltage_3.Add(Convert.ToDouble(reader["Voltage_Phase_3"]));
current_1.Add(Convert.ToDouble(reader["Current_Phase_1"]));
current_2.Add(Convert.ToDouble(reader["Current_Phase_2"]));
current_3.Add(Convert.ToDouble(reader["Current_Phase_3"]));
Meter_datetime.Add(sample_con.ConvertToUnixTimestamp(Convert.ToDateTime(reader["Data_Datetime"])));
device_id = Convert.ToInt32(reader["Device_ID"]);
}
ViewData["energy_kwh"] = energy_kwh;
ViewData["Meter_datetime"] = Meter_datetime;
ViewData["power_kw"] = power_kw;
ViewData["voltage_1"] = voltage_1;
ViewData["voltage_2"] = voltage_2;
ViewData["voltage_3"] = voltage_3;
ViewData["current_1"] = current_1;
ViewData["current_2"] = current_2;
ViewData["current_3"] = current_3;
ViewData["x"] = x;
ViewData["events"] = events;
return View();
above 'x' is the sreen width only
in my view i have created a global getSVG method that takes an array of charts as an argument
$(function () { Highcharts.getSVG = function (charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ' );
svg=svg.replace('</svg>', '</g>');
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="'+ top +'" width="' + width + '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
and also created a global export Charts method that takes an array of charts as an argument, and exporting options as the second argument
Highcharts.exportCharts = function(charts, options) {
// Merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// Post to export server
Highcharts.post(options.url, {
filename: options.filename || 'chart',
type: options.type,
width: options.width,
svg: Highcharts.getSVG(charts)
});
};
after that i have arranged data coming from controller like this
var myArrayX_kwh = [];
var myArrayY_kwh = [];
var myArrayY_power = [];
var myArrayY_voltage_1 = [];
var myArrayY_voltage_2 = [];
var myArrayY_voltage_3 = [];
var myArrayY_current_1 = [];
var myArrayY_current_2 = [];
var myArrayY_current_3 = [];
var arry_kwh = [];
var arry_power = [];
var arry_voltage_1 = [];
var arry_voltage_2 = [];
var arry_voltage_3 = [];
var arry_current_1 = [];
var arry_current_2 = [];
var arry_current_3 = [];
then i have 2 for loops that will push data in array like this
#foreach (var st in ViewData["Meter_datetime"] as List<double?>)
{
#:myArrayX_kwh.push(#st);
}
#foreach (var st in ViewData["energy_kwh"] as List<double?>)
{
#:myArrayY_kwh.push(#st);
}
#foreach (var st in ViewData["power_kw"] as List<double?>)
{
#:myArrayY_power.push(#st);
}
#foreach (var st in ViewData["voltage_1"] as List<double?>)
{
#:myArrayY_voltage_1.push(#st);
}
#foreach (var st in ViewData["voltage_2"] as List<double?>)
{
#:myArrayY_voltage_2.push(#st);
}
#foreach (var st in ViewData["voltage_3"] as List<double?>)
{
#:myArrayY_voltage_3.push(#st);
}
#foreach (var st in ViewData["current_1"] as List<double?>)
{
#:myArrayY_current_1.push(#st);
}
#foreach (var st in ViewData["current_2"] as List<double?>)
{
#:myArrayY_current_2.push(#st);
} #foreach (var st in ViewData["current_3"] as List<double?>)
{
#:myArrayY_current_3.push(#st);
}
for (var i = 0; i < myArrayX_kwh.length; i++) {
arry_kwh.push({ x: myArrayX_kwh[i], y: myArrayY_kwh[i], });
arry_power.push({ x: myArrayX_kwh[i], y: myArrayY_power[i], });
arry_voltage_1.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_1[i], });
arry_voltage_2.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_2[i], });
arry_voltage_3.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_3[i], });
arry_current_1.push({ x: myArrayX_kwh[i], y: myArrayY_current_1[i], });
arry_current_2.push({ x: myArrayX_kwh[i], y: myArrayY_current_2[i], });
arry_current_3.push({ x: myArrayX_kwh[i], y: myArrayY_current_3[i], });
}
then i have initialized and written the code for my charts
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1',
type: 'column',
zoomType: 'xy',
resetZoomButton: {
position: {
align: 'right', // by default
verticalAlign: 'top', // by default
x: -250,
y: 5,
//height: 25
},
relativeTo: 'chart'
}
},
title: {
text: 'Energy vs Date & Time',
style: {
//color: '#FF00FF',
fontWeight: 'bold',
//fontSize: '12px'
//sfont: 'bold 200px Verdana, sans-serif',
}
},
xAxis: {
// categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
type: 'datetime',
// max: new Date().getTime(),
//labels: {
// // format: {value:}
// style: {
// fontSize: '13px',
// fontFamily: 'Verdana, sans-serif'
// }
//}
}, yAxis: {
title: {
text: 'Energy (kWh)',
style: {
//color: '#FF00FF',
fontSize: '12px',
//sfont: 'bold 200px Verdana, sans-serif',
}
}
},
as i am displaying 4 charts so i have done the same as like above with other 3 here the things are working good all the data from DB is showing in charts and if DB is updated then on page refresh it is showed but as i wrote above i don't want to refresh the page
for this i have done
var dt = JSON.stringify({
"arryKwh": arry_kwh,
"arryPower": arry_power,
"arryVoltage_1": arry_voltage_1,
"arryVoltage_2": arry_voltage_2,
"arryVoltage_3": arry_voltage_3,
"arryCurrent_1": arry_current_1,
"arryCurrent_2": arry_current_2,
"arryCurrent_3": arry_current_3
});
after that i have done an ajax call and passed data into success alert to view whether it's having my data or not
(function poll() {
setTimeout(function () {
$.ajax({
type: "POST",
url: "/Home/MultiGraph/",
data:dt,
success: function (data)
{
alert(data)
},
});
poll();
}, 5000);
})();
But when i run the application the alert message display with this
I am missing something but what it is i don't know
I have found SignalR but i think it would be time taking as i have to write all things again
Another solution came to mind is that may be if i set a condition in view or controller in which it checks if the DB is updated than it automatically refresh the page
I am confused any help will be appreciated

JavaScript - Highcharts box plot not displaying

I am having trouble creating a highcharts box-plot graph, I have all the data in the correct format i.e. min, lower quartile, median, upper quartile and max.
I can display the categories but I cannot get it to display the data.
This is my code:
function BoxPlot() {
//ViewBag Variables
var Till = #Html.Raw(Json.Encode(#ViewBag.Tills));
var Per20 = #Html.Raw(Json.Encode(#ViewBag.P20));
var Per30 = #Html.Raw(Json.Encode(#ViewBag.P30));
var Per40 = #Html.Raw(Json.Encode(#ViewBag.P40));
var Per50 = #Html.Raw(Json.Encode(#ViewBag.P50));
var Per60 = #Html.Raw(Json.Encode(#ViewBag.P60));
var Per70 = #Html.Raw(Json.Encode(#ViewBag.P70));
var Per80 = #Html.Raw(Json.Encode(#ViewBag.P80));
var Per90 = #Html.Raw(Json.Encode(#ViewBag.P90));
//Combine the till no with its data
var final = [];
for(var i=0; i < Till.length; i++) {
final.push({
name: Till[i],
p20: Per20[i],
p30: Per30[i],
p40: Per40[i],
p50: Per50[i],
p60: Per60[i],
p70: Per70[i],
p80: Per80[i],
p90: Per90[i],
});
}
console.log(final)
//get the data into the correct format for box plot
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
a: final[i].p20,
b: ((final[i].p30 + final[i].p40) / 2),
c: ((final[i].p50 + final[i].p60) / 2),
d: ((final[i].p70 + final[i].p80) / 2),
e: final[i].p90,
});
}
console.log(formated)
//graph the data
$('#container').highcharts({
chart: {
type: 'boxplot'
},
title: {
text: 'Highcharts Box Plot'
},
legend: {
enabled: true
},
xAxis: {
categories: Till,
title: {
text: 'Till No.'
}
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Values',
data: formated,
tooltip: {
headerFormat: '<em>Till No. {point.key}</em><br/>'
}
}]
});
}
This is an example of the formatted array and the data it contains:
This is how the graph currently looks, you can see the categories array is working but it is not showing the data:
I was able to solve this by changing how I gathered the data, Im not sure if the box plot is case sensitive but by changing the variable names the data displayed
This is the whole code I am using:
function BoxPlot() {
//ViewBag Variables
var Till = #Html.Raw(Json.Encode(#ViewBag.Tills));
var Per20 = #Html.Raw(Json.Encode(#ViewBag.P20));
var Per30 = #Html.Raw(Json.Encode(#ViewBag.P30));
var Per40 = #Html.Raw(Json.Encode(#ViewBag.P40));
var Per50 = #Html.Raw(Json.Encode(#ViewBag.P50));
var Per60 = #Html.Raw(Json.Encode(#ViewBag.P60));
var Per70 = #Html.Raw(Json.Encode(#ViewBag.P70));
var Per80 = #Html.Raw(Json.Encode(#ViewBag.P80));
var Per90 = #Html.Raw(Json.Encode(#ViewBag.P90));
var heading = #Html.Raw(Json.Encode(#ViewBag.QueryTitle));
//Combine the till no with its data
var final = [];
for(var i=0; i < Till.length; i++) {
final.push({
name: Till[i],
p20: Per20[i],
p30: Per30[i],
p40: Per40[i],
p50: Per50[i],
p60: Per60[i],
p70: Per70[i],
p80: Per80[i],
p90: Per90[i],
});
}
console.log(final)
//get the data into the correct format for box plot
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
low: final[i].p20,
q1: ((final[i].p30 + final[i].p40) / 2),
median: ((final[i].p50 + final[i].p60) / 2),
q3: ((final[i].p70 + final[i].p80) / 2),
high: final[i].p90,
});
}
console.log(formated)
var boxData = [];
//boxData.push(formated);
//console.log(boxData);
//graph the data
$('#container').highcharts({
chart: {
type: 'boxplot'
},
title: {
text: heading
},
legend: {
enabled: true
},
xAxis: {
categories: Till,
title: {
text: 'Till No.'
}
},
yAxis: {
title: {
text: 'Distribution'
}
},
series: [{
name: 'Tills',
data:
formated
}]
});
}

Using Highcharts with minutes, seconds and milliseconds as Data not working

I am trying to chart 1000 meters run, data is given via mySQL Database and brings MeterTime and urDate. urDate is on the x-axis and y-axis should hold seconds. But the chart either plots nothing at all, or everything on the zero line.
I understand I need to change how the charts interprets the time, but only the minutes, seconds and milliseconds are provided. Not sure how I can convert it.
Any anyone see on the jsfiddle and check what i might be doing wrong please?
jsfiddle
var chart;
var data = [{"urDate":"2015-03-04","urTime":"00:02:05","MeterTime":"00:15:534250"},{"urDate":"2015-03-06","urTime":"00:02:25","MeterTime":"00:18:019730"}];
var options = {
chart: {
backgroundColor: '#34495e',
plotBackgroundColor: '#2b3c50',
renderTo: 'container',
type: 'line'
},
title: {
text: '',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
name: 'Time'
},
type: 'datetime',
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: []
};
var dataXAxis = [],
dataSeries = [{
data: []
}];
data.forEach(function (va) {
dataXAxis.push(formatDate(va.urDate));
dataSeries[0].data.push(formatDate(va.MeterTime));
});
// And assign the correct format to highcharts
options.xAxis.categories = dataXAxis;
options.series = dataSeries;
// create the first chart
chart = new Highcharts.Chart(options);
function formatDate(d) {
d = new Date(d);
var month = d.getMonth();
var day = d.getDate();
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
return (day + '-' + month + '-' + d.getFullYear());
}
UPDATE
I have changed the jsfiddle to include how the data is now loaded from the mySQL query. Thanks to One, below, who gave me the idea to change how the data came in, rather than changing it once it arrived.
New Code looks like this:
var options = {
chart: {
backgroundColor: '#34495e',
plotBackgroundColor: '#2b3c50',
renderTo: 'container',
type: 'line'
},
title: {
text: '',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
name: 'Seconds'
},
//type: 'datatime', //y-axis will be in milliseconds
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: []
};
var dataXAxis = [], dataSeries = [{data: []}];
data.forEach(function (va) {
dataXAxis.push(formatDate(va.urDate));
console.log('t ' + va.MeterTime);
dataSeries[0].data.push(parseInt(va.MeterTime));
})
// And assign the correct format to highcharts
options.xAxis.categories = dataXAxis;
options.series = dataSeries;
options.yAxis.title.text = 'Seconds';
// create the first chart
chart = new Highcharts.Chart(options);
});
The main difference is how the data comes in:
[{"urDate":"2015-03-04","MeterTime":"15.5343"},{"urDate":"2015-03-06","MeterTime":"18.0197"}]
This comes from a mySQL Query that looks like this:
$isql = "SELECT urDate, time_to_sec(urTime) / (urMiles / 0.00062137) * 1000 AS MeterTime FROM results WHERE uid = " . $_POST['uid'] . " ORDER BY urDate ASC;";
$ires = $mysqli->query($isql);
while ($irow = $ires->fetch_array(MYSQLI_ASSOC)) {
$data_result['userChart'][] = $irow;
}
echo json_encode($data_result);
And the end result, apart from some better styling, is this:
Hope this helps others in the future.
Plotted millisecond as Y axis.
http://jsfiddle.net/kjjn6tn3/3/
secondd = _.map(data , function (v) {return _.reduce(_.map(_.zip(_.map(v['urTime'].split(":"), function(v) {return parseInt(v);}), [60*60,60,1]), function (value , key) {return value[0]*value[1];}), function (x ,y ){ return x+y;})});
dataY = {
name :"pump",
data : secondd
}
same you can do with meter time and plot as Y axis.

Create Line in Highcharts with start and end point

Please look at following example:
<script type="text/javascript">
var $j = jQuery.noConflict();
function recalculateUTCValue(startingUTC, add) {
zeit = new Date(startingUTC);
zeit.setDate(zeit.getDate()+add);
return zeit;
}
function calcDateFromUTC(utc) {
d = new Date(utc);
return d;
}
function getDaysUntilEnd(utc) {
var currentTime = new Date();
var endTime = calcDateFromUTC(utc);
var diff = Math.floor(( Date.parse(endTime) - Date.parse(currentTime) ) / 86400000);
return diff;
}
</script>
<script type="text/javascript">
var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
var TaskChart; // Chart-Objekt
var container = $j('#chart01')[0];
var TaskDuration = new Array();
var startingKW = 298;
// Save starting points to javascript variables for HighCharts
var startingUTC = 1288087223364;
// For a given time point id
var startTimePoint = 0;
var endTimePoint = 0;
TaskDuration = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,216.0,216.0,216.0,198.0,134.0,134.0,134.0,171.0,171.0,171.0,149.0,160.5,160.5,160.5];
// Get first value which is not "0"
var firstValue = 0;
for(var i = 0; i < TaskDuration.length; i++) {
if(TaskDuration[i] != 0) {
firstValue = i;
break;
}
}
// Get largest Y-Value; need for automatically zooming (setExtremes method)
var largest = Math.max.apply(Math, TaskDuration);
var myStartDate;
var myEndDate;
// Check if we have a time point in the query
if(startTimePoint != 0) {
var myStartDate = calcDateFromUTC(startTimePoint);
var myEndDate = calcDateFromUTC(endTimePoint);
} else {
// Otherwise we use the time of first created work item
var myStartDate = recalculateUTCValue(startingUTC, firstValue);
var myEndDate = new Date();
}
</script>
<script type="text/javascript">
$j(document).ready(function() {
TaskChart = new Highcharts.Chart({
credits: {
enabled: false
},
chart: {
renderTo: "chart01",
defaultSeriesType: 'line',
zoomType: 'x',
events: {
load: function(event) {
this.xAxis[0].setExtremes(myStartDate, myEndDate);
this.yAxis[0].setExtremes(0,largest);
}
}
},
title: {
text: "Task Burn Down Chart"
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
week: '%e. %b %Y'
},
labels: {
align: 'right',
rotation: -60,
x: 5,
y: 15
},
offset: 10
},
yAxis: {
title: {
text: "Number of Hours"
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>' + Highcharts.dateFormat('%d.%m', this.x) +': '+ this.y;;
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
}
},
series: [
{
name: 'Hours',
pointStart: startingUTC,
pointInterval: 24*60*60*1000,
data: TaskDuration
},
{
type: 'line',
name: 'Regression Line',
data: [[myStartDate, 216], [myEndDate, 50]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
}]
});
});
</script>
http://jsfiddle.net/JwmuT/8/
The goal is to create a Highchart line with starting point from X-Value 26th January and with the end point on the X-Value 7th February. Corresponding Y-Values are "260" and "0".
How to create a simple line with these to points in HighCharts? Maybe Highcharts is able to do a linear regression on the fly?!
I have found this demo but I do not know how to pass correctly X-Values in the Date format.
Highcharts doesn't calculate any type of regression or trend lines. In example you have posted, data is calculated before, and Highcharts just displays that. However there is known plugin for trendline: https://github.com/virtualstaticvoid/highcharts_trendline

Categories

Resources