How to create a chart in MVC Having three values to show - asp.net-mvc

I am new in MVC 5, not having much idea about creating chart.
i need to create a chart which will show the Four values from a table as such below FormatName,Month,SuccessCount, FailCount .
I want to show success and Failcount on the basis of Month for each Format.
Formats are client names.
I tried with several sites , but no idea how to show the three values.
Month FormatName SuccessCount FailedCount
Jan HPCL 20 32
Feb FG 23 0
Mar abcd 13 34
Apr Test 12 23
Above is the table which i want to show on chart.Unfortunately i cannot add image as it is not permitted yet on stackoverflow.
I have used below method to show the data in chart.
`public List BindFormatByMonth(string status)
{
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1 = PBMSCommon.Database.ExecuteDataSet("usp_sel_DedupeDetails", status).Tables[0]; // success records
List ochartmodel = new List();
foreach (DataRow row in dt1.Rows)
{
FormatStatus omodel = new FormatStatus();
omodel.FormatName = Convert.ToString(row["NVFormatCode"]);
omodel.month = Convert.ToString(row["Month"]);
omodel.successCount = Convert.ToInt32(row["Status"]);
ochartmodel.Add(omodel);
}`
any help will be appreciated.
Pooja

You can use vertical bar chart for your requirement. I will suggest you to use chart.js. It responsive and user friendly.
So I have added a fiddler here! It would be use full to you!
Fiddle
Html:
<canvas id="myChart" width="400" height="400"></canvas>
Javascript:
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["Jan", "Feb", "Mar"],
datasets: [{
label: "HPCL",
backgroundColor: "skyblue",
data: [20, 32, 12]
}, {
label: "FG ",
backgroundColor: "maroon",
data: [23, 10, 15]
}, {
label: "abcd",
backgroundColor: "green",
data: [13, 34, 16]
}, {
label: "test",
backgroundColor: "violet",
data: [12, 23, 16]
}]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
barValueSpacing: 20,
scales: {
yAxes: [{
ticks: {
min: 0,
}
}]
}
}
});
Fiddle

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>

highstock charts - button for date range

in my application I use angular Highstock for charts. I have a lot of data (many millions), and now i want to put the existing buttons for set date range (1week, 1 month, 3 months, 1year, all), but also to click on any button to send a new request to the server to not accumulating data. Example, if pressed button "one week", that only the server retrieves the data for one week, if you click on a button to one month, to take data for a single month. I do not want to call unnecessary data, and that the server slows down, if I'm looking for data for one month, and the server comes back to me all data. Here is the code. Thanks in advance
> https://jsfiddle.net/tf7pr1ft/
Thnx to #Grzegorz Blachliński i fix this. here is code
$scope.chartConfig1 = {
xAxis: {
ordinal: false,
//za dodat date range postavit events i range selectors
events : {
afterSetExtremes: getDateRange //here i add my custom function
}
},
yAxis: {
plotLines: [{
color: '#FF0000',
width: 1,
value: 11.50,
label: {text: '11.50'}
}]
},
options: {
chart: {
zoomType: 'x',
backgroundColor: 'rgba(255, 255, 255, 1)',
polar: true,
type: 'line',
borderRadius: 5
},
legend: {
enabled: true
},
rangeSelector: {
selected : 0, //here i defined default range
enabled: true,
inputStyle: {
color: 'black'
}
},
navigator: {
enabled: true
}
},
series: [],
title: {
text: 'Solar and Battery voltage average'
},
useHighStocks: true
},
$scope.chartConfig1.series.push({
id: 1,
name: "Solar voltage average",
data: $scope.data[0],
tooltip: {
valueDecimals: 2
}
},   {
id: 2,
name: "Battery voltage average",
data: $scope.data[1],
tooltip: {
valueDecimals: 2
}
}
);
and here is my custom function
getDateRange = function (e) {
var date1 = new Date(e.min);
var date2 = new Date(e.max);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$http.get(serviceBase + 'aaaaa/aaaaaa/' + $stateParams.klupaID + '/aaaaaaa?days=' + diffDays, function(data){
//ukoliko buden dodavat još koji config obavezno dodat broj koliko ih ima na i<=8
for (i=1; i<=8; i++){
$scope.chartConfigString = 'chartConfig' + i;
$scope.chartConfigString.series[0].setData(data);
$scope.chartConfigString.hideLoading();
}
});
};
Now i have another problems, i want to have four selectors (buttons), 1months, 3months, 1year and ALL. I set default range, when open app, on 1month, and here is problem. Buttons for another range is disabled, beacause i get data from url only for one month. I want to have enabled all buttons for select any range. Thnx

How do you set the stack order of the series in a stacked bar chart?

I have been able to control the stacking order of highchart by setting the index field in the series objects like this:
series: [
{
name: 'My Products',
data: randomRange(12, 7, 61), // Just random test data for now.
stack: 'ProductType',
index: 1 // Here index sets the stacking order in the bar. This will be on the bottom.
}, {
name: 'Total',
data: randomRange(12, 233, 240), // Just random test data for now.
stack: 'ProductType',
index: 0 // This will be on the top.
}
]
As you can see, a lower index number will be stacked higher in the bar.
Now I am trying to refresh the series, but the stacking order gets lost and I cannot set the index:
var chart1 = $('#quantityPerMonthChart1').highcharts();
chart1.series[1].setData(randomRange(12, 233, 240), false);
chart1.series[1].index = 0; // Doesn't work.
chart1.series[0].setData(randomRange(12, 7, 61), false);
chart1.series[0].index = 1; // Doesn't work.
chart1.redraw();
index is option of a series that can be update using Series.update() - it can be also used to update data of the series as data is another option.
$(function() {
var chart = Highcharts.chart('container', {
chart: {
type: 'column'
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
data: [1, 2, 3, 4, 5, 4],
index: 1
}, {
data: [6, 4, 5, 6, 7, 4],
index: 2,
id: 's2'
}]
});
$('#button').click(function() {
chart.get('s2').update({index: 0});
});
});
Example: http://jsfiddle.net/ae7Ljmc7/
There seemed to be no documentation or other examples on the net on how to do this. So I experimented and found out that the index is set naturally by the order in which you add to the series array. So I could change my seed series to this:
series: [
{
name: 'Total', // The series you add first will get stacked on the top
data: randomRange(12, 233, 240),
stack: 'ProductType'
}, {
name: 'My Products',
data: randomRange(12, 7, 61),
stack: 'ProductType'
}
]
Then when I refresh the chart data with different options, I do this:
$('#productType').on('change', function() {
var chart1 = $('#quantityPerMonthChart1').highcharts();
// These series already have an index (which affects stack order).
// Here it is unchanged.
chart1.series[0].setData(randomRange(12, 233, 240), false);
chart1.series[1].setData(randomRange(12, 7, 61), false);
chart1.redraw();
});

Highstock Issue - Can't draw and plot chart correctly

I'm working on project to display stock information using Highstock.
Question 1:
I tried to display ohlc data using ohlc graph, high and low using areasplinerange graph, and volume using column chart.
Everything works fine, if i zoom 1m, 3m, 6m, YTD, and 1y. Here is the snapshot. link1. But if zoom to All, The graph messed up like this link2.
Am i wrong in my coding or it's bug?
Question 2:
In the same chart, I have code to change the type of graph from ohlc to line. It works fine when I zoom to 1m, 3m. Here is the snapshot link3. But it show me no line chart when i zoom to 6m, 1y, and All. Here is the snapshot link4.
How can this happen?
Thank you for your help.
The Code:
Here is the code that i used to display the chart
$.getJSON(url, function (data1) {
$.getJSON(urlprediction, function (data2) {
var ohlc = [],
volume = [],
closed = [],
forecast = [],
dataLength1 = data1.length;
dataLength2 = data2.length;
for (i = 0; i < dataLength1; i++) {
ohlc.push([
data1[i][0], // the date
data1[i][1], // open
data1[i][2], // high
data1[i][3], // low
data1[i][4] // close
]);
closed.push([
data1[i][0], // the date
data1[i][4] // close
]);
volume.push([
data1[i][0], // the date
data1[i][5] // the volume
])
}
for (i = 0; i < dataLength2; i++) {
forecast.push([
data1[i][0], // the date
data1[i][1],
data1[i][2], // close
])
}
// set the allowed units for data grouping
var groupingUnits = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: title
},
yAxis: [{
title: {
text: 'OHLC'
},
height: 360,
lineWidth: 2
}, {
title: {
text: 'Volume'
},
top: 433,
height: 100,
offset: 0,
lineWidth: 2
}],
series: [{
type: 'ohlc',
name: stockname,
data: ohlc,
}, {
type: 'areasplinerange',
name: stockname,
data: data2,
}, {
type: 'column',
name: 'Volume',
data: volume,
yAxis: 1,
}]
});
});
});

Custom YTD Option in HighStock Range Selector

Using the Highstock charting library, Is there any way using the Highstock Range selector to display a custom YTD option?
Current when you use a type of 'ytd' in the range selector, it defaults to using the calendar year. For my use case (and i would have thought for financial institutions as well) i need to display data running from 1st April - 31st March as a 'ytd' option
It's probably not possible without hacking sources, find in Highstock:
else if (type === 'ytd') {
now = new Date(dataMax);
year = now.getFullYear();
newMin = rangeMin = mathMax(dataMin || 0, Date.UTC(year, 0, 1));
now = now.getTime();
newMax = mathMin(dataMax || now, now);
}
So as you can see, dates are hardcoded. You can change them to needed.
Here's how i've done it. Doesn't cope with looking at a previous Financial YTD (Which is a common use case for what i need it for), but i'm sure i could hack something up to do it.
JSFiddle here
$(function() {
var startDate = new Date("April 01, 2012 00:00:00");
var today = new Date();
var count = parseInt((today.getTime() - startDate)/(24*3600*1000)) -1;
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected: 1,
buttonTheme: {
width:100
},
buttons: [{
type: 'ytd',
count: 1,
text: 'Calendar YTD'
},
{
type: 'day',
count: count,
text: 'Financial YTD'
}]
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data,
tooltip: {
valueDecimals: 2
}
}]
} );
});
});

Resources