Google Combo Charts? - asp.net-mvc

I have 4 entities and I show them for 4 days. But first and last days I cant see other 2 entities.In 3 August I cant see T0,T1. In 6 August I cant see T2,T3.
Codes
var evalledData = eval("(" + result.chartData + ")");
var ac = new google.visualization.ComboChart($("#chart_div_ay").get(0));
ac.draw(new google.visualization.DataTable(evalledData, 0.5), {
//title: 'Son 7 günlük sayaç okumalarının toplamı.',
width: '100%',
height: 300,
vAxis: { title: "kW" },
hAxis: { title: "Gün" },
seriesType: "bars",
series: { 5: { type: "line"} }
});
Controller:
public ActionResult MusteriSayaclariOkumalariChartDataTable(DateTime startDate, DateTime endDate, int? musteri_id)
{
IEnumerable<TblSayacOkumalari> sayac_okumalari = entity.TblSayacOkumalari;
var sonuc = from s in sayac_okumalari
where s.TblSayaclar.musteri_id == musteri_id && s.okuma_tarihi.Value >= startDate && s.okuma_tarihi.Value <= endDate
group s by new { date = new DateTime(((DateTime)s.okuma_tarihi).Year, ((DateTime)s.okuma_tarihi).Month, ((DateTime)s.okuma_tarihi).Day) } into g
select new
{
okuma_tarihi = g.Key,
T1 = g.Sum(x => x.kullanim_T1) / 1000,
T2 = g.Sum(x => x.kullanim_T2) / 1000,
T3 = g.Sum(x => x.kullanim_T3) / 1000,
T4 = g.Sum(x => x.kullanim_T0) / 1000
};
//Get your data table from DB or other source
DataTable chartTable = new DataTable();
chartTable.Columns.Add("Tarih").DataType = System.Type.GetType("System.DateTime");
chartTable.Columns.Add("T1").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("T2").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("T3").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("Toplam").DataType = System.Type.GetType("System.Double");
foreach (var item in sonuc)
{
chartTable.Rows.Add(item.okuma_tarihi.date, item.T1.Value, item.T2.Value, item.T3.Value, item.T4.Value);
}
//convert datetime value to google datetype, if your first column is date
Bortosky
.Google
.Visualization
.GoogleDataTable
.SetGoogleDateType(chartTable.Columns["Tarih"],
Bortosky.Google.Visualization.GoogleDateType.Date);
//convert DataTable to GoogleDataTable
var googleDataTable =
new Bortosky.Google.Visualization.GoogleDataTable(chartTable);
//Pass the google datatable to UI as json string
return new JsonResult
{
Data = new
{
success = true,
chartData = googleDataTable.GetJson()
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
This action return json as google examples custom data.
evalledData output:
Is there any option about this problem?
Thanks.

I recently had to build a chart like this. Please consider my code for your solution:
Put this in your Controller:
<EmployeeAuthorize()>
Function WeightAreaChartData() As JsonResult
Dim myData = db.Tbl_Weights.Where(Function(x) x.Weight_Employee_ID).OrderBy(Function(x) x.Weight_Create_Date)
Dim data = New List(Of Object)
data.Add(New Object() {"Date", "Your Weight"})
For Each i As Tbl_Weight In myData
data.Add(New Object() {DateTime.Parse(i.Weight_Create_Date).Day, i.Weight_Amount})
Next
Return Json(data, JsonRequestBehavior.AllowGet)
End Function
Put this in your view; changing the $.post() URL accordingly:
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.post('/Weight/WeightAreaChartData', {},
function (data) {
var tdata = new google.visualization.arrayToDataTable(data);
var options = {
title: 'Weight Lost & Gained This Month',
hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} },
vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08'} },
chartArea: { left: 50, top: 30, width: "75%" },
colors: ['#FF8100']
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(tdata, options);
});
}
</script>
<div id="chart_div" style="width: 580px; height: 200px;"></div>
To fix your specific issue of the bars being cut off, I believe you can use this in your options:
hAxis: {
viewWindowMode: 'pretty'
}
Like this:
var options = {
title: 'Weight Lost & Gained This Month',
hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} },
vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08' } },
chartArea: { left: 50, top: 30, width: "75%" },
colors: ['#FF8100', 'blue'],
hAxis: {
viewWindowMode: 'pretty'
}
};

Related

Kendo Gantt Timeline in 30 minute increments?

I am using the Kendo Gantt chart with ASP.NET Core MVC, and I would like to get the Day view timeline to show in 30 minute increments vs. 1 hour increments. The working hours I'm trying to display for each day are 7:00 AM to 3:30 PM, but I cannot get that 3:30 PM end of day to display.
Here is an example of getting a time header template using the jquery kendo gantt chart
<div id="gantt"></div>
<script>
$("#gantt").kendoGantt({
dataSource: [{
id: 1,
orderId: 0,
parentId: null,
title: "Task1",
start: new Date("2014/6/17 9:00"),
end: new Date("2014/6/17 11:00")
}],
views: [
{ type: "day", timeHeaderTemplate: kendo.template("#=kendo.toString(start, 'T')#") },
{ type: "week" },
{ type: "month" }
]
});
</script>
However, I can't figure out how get that template to show the 30 minute increments, or if there is a different way to accomplish this. Essentially, I want it to look like the Kendo Scheduler Timeline view shown here:
I opened a support ticket with Telerik and got an answer that while there is no built-in way to do this with the Gantt component, one way to implement would be to create a custom view as demonstrated here: https://docs.telerik.com/kendo-ui/controls/scheduling/gantt/how-to/creating-custom-view
Custom view example code:
<div id="gantt"></div>
<script type="text/javascript">
var gantt;
$(function StartingPoint() {
kendo.ui.GanttCustomView = kendo.ui.GanttView.extend({
name: "custom",
options: {
yearHeaderTemplate: kendo.template("#=kendo.toString(start, 'yyyy')#"),
quarterHeaderTemplate: kendo.template("# return ['Q1', 'Q2', 'Q3', 'Q4'][start.getMonth() / 3] #"),
monthHeaderTemplate: kendo.template("#=kendo.toString(start, 'MMM')#")
},
range: function(range) {
this.start = new Date("01/01/2013");
this.end = new Date("01/01/2016");
},
_generateSlots: function(incrementCallback, span) {
var slots = [];
var slotStart = new Date(this.start);
var slotEnd;
while (slotStart < this.end) {
slotEnd = new Date(slotStart);
incrementCallback(slotEnd);
slots.push({ start: slotStart, end: slotEnd, span: span });
slotStart = slotEnd;
}
return slots;
},
_createSlots: function() {
var slots = [];
slots.push(this._generateSlots(function(date) { date.setFullYear(date.getFullYear() + 1); }, 12));
slots.push(this._generateSlots(function(date) { date.setMonth(date.getMonth() + 3); }, 3));
slots.push(this._generateSlots(function(date) { date.setMonth(date.getMonth() + 1); }, 1));
return slots;
},
_layout: function() {
var rows = [];
var options = this.options;
rows.push(this._slotHeaders(this._slots[0], kendo.template(options.yearHeaderTemplate)));
rows.push(this._slotHeaders(this._slots[1], kendo.template(options.quarterHeaderTemplate)));
rows.push(this._slotHeaders(this._slots[2], kendo.template(options.monthHeaderTemplate)));
return rows;
}
});
gantt = new kendo.ui.Gantt($("#gantt"),
$.extend({
columns: [
{ field: "id", title: "ID", sortable: true, editable: false, width: 30 },
{ field: "title", title: "Title", sortable: true, editable: true, width: 100 },
{ field: "start", title: "Start Time", sortable: true, editable: true, format: "{0:MM/dd/yyyy HH:mm}", width: 100 },
{ field: "end", title: "End Time", sortable: true, editable: true, format: "{0:MM/dd/yyyy HH:mm}", width: 100 }
],
views: [
"week",
{ type: "kendo.ui.GanttCustomView", title: "Quaterly", selected: true }
],
listWidth: 500,
dataBound: function() {
var height = this.timeline.view().header.height();
this.list.thead.find('tr').css('height',height);
},
dataSource: {
data: [{ id: 1, parentId: null, percentComplete: 0.2, orderId: 0, title: "foo", start: new Date("05/05/2014 09:00"), end: new Date("06/06/2014 10:00") },
{ id: 2, parentId: null, percentComplete: 0.4, orderId: 1, title: "bar", start: new Date("07/06/2014 12:00"), end: new Date("08/07/2014 13:00") }]
},
dependencies: {
data: [
{ id: 1, predecessorId: 1, successorId: 2, type: 1 }
]
}
}, {})
);
});
</script>

why x-axis showing alternate months rather every month?

Following is my highcharts config, can you help me to why my alternate months are coming, and if i want to show every month, how do i do it ? Also, to change width of the bar if showing every month.
Highcharts.chart("energy_chart", {
chart: {
type: "column",
spacingBottom: 15,
spacingTop: 10,
spacingLeft: 10,
spacingRight: 10,
backgroundColor: "#f2f2f2",
events: {
load: function() {
var fin = new Date();
var finDate = fin.getDate();
var finMonth = fin.getMonth();
var finYear = fin.getFullYear();
var ini = new Date();
ini.setFullYear(ini.getFullYear() - 1);
var iniDate = ini.getDate();
var iniMonth = ini.getMonth();
var iniYear = ini.getFullYear();
if (this.yAxis[0].dataMax == 0) {
this.yAxis[0].setExtremes(null, 1);
}
//this.yAxis.set
console.log(new Date(Date.UTC(iniYear, iniMonth, iniDate)))
console.log(new Date(Date.UTC(finYear, finMonth, finDate)))
this.xAxis[0].setExtremes(
Date.UTC(iniYear, iniMonth, iniDate),
Date.UTC(finYear, finMonth, finDate)
);
},
drilldown: function(e) {
console.log('drilldown')
var charts_this = this;
var inidrillDate = new Date(e.point.x);
setTimeout(function() {
inidrillDate.setDate(0);
inidrillDate.setMonth(inidrillDate.getMonth());
var DateinidrillDate = inidrillDate.getDate();
var MonthinidrillDate = inidrillDate.getMonth();
var YearinidrillDate = inidrillDate.getFullYear();
var findrillDate = inidrillDate;
findrillDate.setMonth(findrillDate.getMonth() + 1);
findrillDate.setDate(findrillDate.getDate() - 1);
var DatefindrillDate = findrillDate.getDate();
var MonthfindrillDate = findrillDate.getMonth();
var YearfindrillDate = findrillDate.getFullYear();
console.log(Date.UTC(
YearinidrillDate,
MonthinidrillDate,
DateinidrillDate
))
console.log(Date.UTC(
YearfindrillDate,
MonthfindrillDate,
DatefindrillDate
))
charts_this.xAxis[0].setExtremes(
Date.UTC(
YearinidrillDate,
MonthinidrillDate,
DateinidrillDate
),
Date.UTC(
YearfindrillDate,
MonthfindrillDate,
DatefindrillDate
)
);
if (charts_this.yAxis[0].dataMax === 0) {
charts_this.yAxis[0].setExtremes(null, 1);
}
}, 0);
}
}
},
title: {
text: '<p className="energy_gen">Energy Generated</p>'
},
exporting: { enabled: false },
xAxis: {
type: "datetime",
labels: {
step: 1
},
dateTimeLabelFormats: {
day: "%e"
}
},
yAxis: {
title: {
text: "kWh"
}
},
credits: {
enabled: false
},
plotOptions: {
series: {
cursor: "pointer",
dataLabels: {
enabled: true,
format: "{point.y}"
},
color: "#fcd562",
point:{
events:{
click:function(event){
}
}
}
}
}
},
tooltip: {
formatter: function() {
if (this.point.options.drilldown) {
return (
"Energy generated: <b> " +
this.y +
"</b> kWh " +
"<br>" +
Highcharts.dateFormat("%b %Y", new Date(this.x))
);
} else {
return (
"Energy generated: <b> " +
this.y +
"</b> kWh " +
"<br>" +
Highcharts.dateFormat("%e %b %Y", new Date(this.x))
);
}
}
},
series: [{'data':obj.data,'name':obj.name,"color":"#4848d3"}],
drilldown: {
series: obj.data
}
});
Also, attaching the screenshot of the rendered highchart with drilldown.
,
Now drilldown graph(same sort a issue)
EDIT:
It turnsout to be a zoom issue, i.e if i zoomout enough, then it shows all points. So, how to show every point without zooimg out .
Working fiddle:
http://jsfiddle.net/gkumar77/w9ngp63u/5/
Use tickInterval property and set it to one month:
xAxis: {
type: "datetime",
tickInterval: 30 * 24 * 3600 * 1000,
labels: {
step: 1
},
dateTimeLabelFormats: {
day: "%e"
}
}
Live demo: http://jsfiddle.net/BlackLabel/q5coany2/
API: https://api.highcharts.com/highcharts/xAxis.tickInterval

Data not getting displayed in jqgrid

I am using jqgrid to display,sort and filter records. At the moment, I have go the js code working, but I think there is something wrong with my controller code, that is not populating the grid. I can see only an empty blak jqgrid with the message "No records to display". Please let me know whats going wrong.
Here is my code:
Controller:
public JsonResult GetData(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pagesize = rows;
var custList = db.Customers.Select(
c => new
{
c.ID,
c.Company,
c.FirstName,
c.EMail,
c.Status
});
int totalCustomers = custList.Count();
var totalPages = (int)Math.Ceiling((float)totalCustomers / (float)rows);
if(sord.ToUpper() == "DESC")
{
custList = custList.OrderByDescending(s => s.FirstName);
custList = custList.Skip(pageIndex * pagesize).Take(pagesize);
}
else
{
custList = custList.OrderBy(s => s.FirstName);
custList = custList.Skip(pageIndex * pagesize).Take(pagesize);
}
var jsonData = new
{
total = totalPages,
page,
customers = totalCustomers,
rows = custList
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Solved my problem. Dint know I would get the solution so quickly. I removed all the existing code from the controller and just added this:
public JsonResult GetData()
{
var customers = db.Customers.Select(m => new { ID = m.ID, Company = m.Company, FirstName = m.FirstName, Email = m.EMail, Status = m.Status }).ToList();
return Json(customers, JsonRequestBehavior.AllowGet);
}
This is all it needs,just two lines of code, rest of the functionalities, ie paging, sorting, filtering is already provided by jqwidgets:) Hope this helps someone who was facing a similar problem as mine.
The script is as follows:
var source =
{
//localdata: GetData(),
url: '/Client/GetData',
datatype: "json",
mtype: 'POST',
datafields: [
{ name: 'ID', type: 'int' },
{ name: 'Company' },
{ name: 'FirstName' },
{ name: 'EMail' },
{ name: 'Status' }
]
};
var dataAdapter = new $.jqx.dataAdapter(source);
// initialize jqxGrid
$("#jqxgrid").jqxGrid(
{
source: dataAdapter,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ text: 'Client Id', datafield: 'ID', width: 200 },
{ text: 'Company', datafield: 'Company', width: 200 },
{ text: 'Username', datafield: 'FirstName', width: 180 },
{ text: 'Email', datafield: 'EMail', width: 100 },
{ text: 'Status', datafield: 'Status', width: 140 }
]
});
});

Highcharts - combining column chart with scatter chart

I have one column chart, representing two categories on X-axis - ARRIVALS and DEPARTURES. Then, I have 4 series representing different commodities, one commodity per each category. This will end up in having 8 columns draw on the chart.
What I'm trying to do, is to add a scatter chart, representing one point per each bar ( a total of 8 points), but unfortunately, I only can add one point per category. Can this be implemented?
Here is the code that I used for this (it is MVC .NET):
Highcharts barChartArrivalsDepartures = new Highcharts("ArrivalsDepartures")
.InitChart(new Chart
{
BorderColor = Color.Black,
BorderRadius = 0,
BorderWidth = 2
})
.SetTitle(new Title { Text = "Arrivals and Departures" })
.SetXAxis(new XAxis { Categories = new[] { "Arrivals", "Departures"} })
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle { Text = "Count [t]" }
})
.SetLegend(new Legend
{
Layout = Layouts.Vertical,
Align = HorizontalAligns.Left,
VerticalAlign = VerticalAligns.Top,
X = 290,
Y = 0,
Floating = true,
BackgroundColor = new BackColorOrGradient(new Gradient
{
LinearGradient = new[] { 0, 0, 0, 400 },
Stops = new object[,]
{
{ 0, Color.FromArgb(13, 255, 255, 255) },
{ 1, Color.FromArgb(13, 255, 255, 255) }
}
}),
Shadow = true
})
.SetTooltip(new Tooltip { Formatter = #"function() { return ''+ this.x +': '+ this.y +' tones'; }" })
.SetSeries(new[]
{
new Series { Type = ChartTypes.Column, Name = "Coal", Data = new Data(new object[] { 49.9, 71.5 }), PlotOptionsColumn = new PlotOptionsColumn { PointPadding = 0.2, BorderWidth = 0 } },
new Series { Type = ChartTypes.Column, Name = "Magnetite", Data = new Data(new object[] { 48.9, 38.8 }) , PlotOptionsColumn = new PlotOptionsColumn { PointPadding = 0.2, BorderWidth = 0 } },
new Series { Type = ChartTypes.Column, Name = "Iron Ore", Data = new Data(new object[] { 83.6, 78.8 }) , PlotOptionsColumn = new PlotOptionsColumn { PointPadding = 0.2, BorderWidth = 0 } },
new Series { Type = ChartTypes.Column, Name = "Grain", Data = new Data(new object[] { 42.4, 33.2 }) , PlotOptionsColumn = new PlotOptionsColumn { PointPadding = 0.2, BorderWidth = 0 } },
new Series
{
Type = ChartTypes.Scatter,
Name = "Target Coal",
Color = ColorTranslator.FromHtml("#FF0000"),
//Data = new Data(new object[] { new object[] {40}, new object[] {80}}),
Data = new Data(new object[] { 15, 50} ),
PlotOptionsScatter = new PlotOptionsScatter
{
Marker = new PlotOptionsScatterMarker
{
Symbol = "diamond",
Radius = 3
}
}
}
})
It's not solution in .net but general idea is to calculate x-value for each of scatter points, for example: http://jsfiddle.net/3bQne/206/
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
},
xAxis: {
categories: ['+', '-']
},
series: [{
data: [1,2],
id: 'first',
stack: 0
}, {
data: [3,5],
id: 'second',
stack: 0
}, {
data: [[-0.15,1],[0.85,2]],
linkedTo: 'first',
type: 'scatter'
}, {
data: [[0.15,3],[1.15,5]],
linkedTo: 'second',
type: 'scatter'
}]
});

jqGrid parameters. Can't be passed

I call web-service to fill jqGrid and wants to pass parameters to it
I use the following code (client side):
jQuery('#EmployeeTable').jqGrid({
datatype: function () {
var params = new Object();
params.page = 10;
params.Filter = true;
params.DateStart = null;
params.DateEnd = null;
params.TagID = null;
params.CategoryID = 3;
params.StatusID = 1;
params.IsDescription = true;
$.ajax({
url: '/Admin/IdeasJSON',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#EmployeeTable")[0];
grid.addJSONData(data);
}
},
error: function () {
alert("Error with AJAX callback");
}
});
},
also, there is propotype of web-method (MVC):
public JsonResult IdeasJSON(int? page, bool? Filter, DateTime? DateStart, DateTime? DateEnd, int? TagID, int? CategoryID, int? StatusID, bool? IsDescription)
Why all these parameters are null?
[ADDED 04/11]
jQuery(document).ready(function () {
var StatusID = null, Filter = null, page = null, DateStart = null, DateEnd = null, TagID = null, CategoryID = null, IsDescription = null;
if (jQuery.url.param('StatusID') != null) {
StatusID = jQuery.url.param('StatusID');
}
if (jQuery.url.param('Filter') != null) {
Filter = jQuery.url.param('Filter');
}
if (jQuery.url.param('page') != null) {
page = jQuery.url.param('page');
}
if (jQuery.url.param('DateStart') != null) {
DateStart = jQuery.url.param('DateStart');
}
if (jQuery.url.param('DateEnd') != null) {
DateEnd = jQuery.url.param('DateEnd');
}
if (jQuery.url.param('TagID') != null) {
TagID = jQuery.url.param('TagID');
}
if (jQuery.url.param('CategoryID') != null) {
CategoryID = jQuery.url.param('CategoryID');
}
if (jQuery.url.param('IsDescription') != null) {
IsDescription = jQuery.url.param('IsDescription');
}
jQuery('#EmployeeTable').jqGrid({
url: '/Admin/IdeasJSON',
datatype: 'json',
postData: { page: page, Filter: Filter, DateStart: DateStart, DateEnd: DateEnd, TagID: TagID, StatusID: StatusID, CategoryID: CategoryID, IsDescription: IsDescription },
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Logged By', 'Logging Agency (ID)', 'Title', 'Status', 'Points', 'Categories', 'Created Date', 'Description', 'Jira ID#', 'Portal Name', '', '', '', '', '', '', ''],
colModel: [
{ name: 'LoggedBy', width: 100 },
{ name: 'LoggingAgencyID', width: 85 },
{ name: 'Title', width: 100 },
{ name: 'Status', width: 100 },
{ name: 'Points', width: 40, align: 'center' },
{ name: 'Categories', width: 100 },
{ name: 'CreatedDate', width: 80, formatter: ndateFormatter },
{ name: 'Description', width: 300 },
{ name: 'JiraID', width: 55 },
{ name: 'PortalName', width: 100 },
{ name: 'IdeaID', width: 25, formatter: ActionDescriptionFormatter },
{ name: 'IdeaID', width: 25, formatter: ActionEditFormatter },
{ name: 'IdeaID', width: 25, formatter: ActionDeleteFormatter },
{ name: 'IdeaGridCommentsAndSubideas', width: 25, formatter: ActionIdeaGridCommentsAndSubideas },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridCountVotes },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridLinkIdeas },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridIdeaType },
],
pager: '#EmployeeTablePager',
width: 1000,
viewrecords: true,
caption: 'Idea List',
excel: true
}).jqGrid('navGrid', '#EmployeeTablePager', {
add: false,
edit: false,
del: false,
search: false,
refresh: false
}).jqGrid('navButtonAdd', '#EmployeeTablePager', {
caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: ReturnExcel,
position: "last"
}).jqGrid('navButtonAdd', '#EmployeeTablePager', {
caption: " Export to CSV ",
buttonicon: "ui-icon-bookmark",
onClickButton: ReturnCSV,
position: "last"
});
});
You should not use datatype as the function to use the JSON data. Probably you used template of very old examples.
For example in the "UPDATED" part of the answer you could find full demo project which demonstrate how to use jqGrid in ASP.MVC 2.0 inclusive paging, sorting and filtering/advanced searching.
If you want post some additional parameters to the server as a part of jqGrid request you should use postData parameters in the form postData: {CategoryID: 3, StatusID: 1, IsDescription:true, Filter: true}

Resources