Does anyone have a simple example of populating a Highchart with data from a MS SQL DB using DotNet.Highcarts?
I have the demo working with static data
Highcharts chart = new Highcharts("chart")
.SetCredits(new Credits { Enabled = false })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetTitle(new Title { Text = "Membership Overview" })
.SetXAxis(new XAxis { Categories = new[] { "Paid Members", "Active Members", "Retained Members", "New Members", "Lapsed Members" } })
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle { Text = "Total Members" }
})
.SetTooltip(new Tooltip { Formatter = "function() { return ''+ this.series.name +': '+ this.y +''; }" })
.SetPlotOptions(new PlotOptions { Bar = new PlotOptionsBar { Stacking = Stackings.Normal } })
.SetSeries(new[]
{
new Series { Name = "Total", Data = new Data(new object[] { 441, 441, 22, 30, 610 }) }
});
How can I change the Series to accept data from my DB?
Assuming I need to connect to DB like so:
var newcustomer = db.Customer;
Then do something like this:
new Series
{
Name = "Total",
Data = new Data(newcustomer.Select(x => ............
Any help would be appreciated!
For anyone else having a similar issue...
var paidmembers = (from c in db.Customer
where c.CustomerStatusID == 1
select c).Count();
var activemembers = (from c in db.Customer
where c.CustomerStatusID == 2
select c).Count();
new Series {
Name = "Category",
Data = new Data(new object[] {paidmembers, activemembers})
}
Related
Im using dotnethighcharts and want the columns to have a pointwidth=20, but I cant get it to work with dotnethighcharts, any suggestions how to make that?
Highcharts chart;
chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetXAxis(new XAxis
{
Categories = new[] { "1", "2" },
Title = new XAxisTitle { Text = string.Empty }
})
.SetPlotOptions(new PlotOptions
{
Bar = new PlotOptionsBar
{
DataLabels = new PlotOptionsBarDataLabels { Enabled = true }
},
})
.SetSeries(new[]
{
new Series {Name = "1", Data = new Data(new object[] {1})},
new Series {Name = "2", Data = new Data(new object[] {4})}
});
Here is an example how to us pointwidth
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/column-pointwidth-20/
The answer - I was missing this
Column = new PlotOptionsColumn
{
PointPadding = 0.2,
PointWidth = 40,
BorderWidth = 0
}
Here is all code
Highcharts chart;
chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetXAxis(new XAxis
{
Categories = new[] { "1", "2" },
Title = new XAxisTitle { Text = string.Empty }
})
.SetPlotOptions(new PlotOptions
{
Column = new PlotOptionsColumn
{
PointPadding = 0.2,
PointWidth = 40,
BorderWidth = 0
},
Bar = new PlotOptionsBar
{
DataLabels = new PlotOptionsBarDataLabels { Enabled = true }
},
})
.SetSeries(new[]
{
new Series {Name = "1", Data = new Data(new object[] {1})},
new Series {Name = "2", Data = new Data(new object[] {4})}
});
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'
}]
});
I m using dotnetHightcharts
BasicColumnChart
public static Highcharts BasicColumnChart(Series[] Series, string[] Categories, string Title = "", string SubTitle = "", string XAxisTitle = "", string YAxisTitle = "", string ToolTipFormat = "", string YAxisLabel = "")
{
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column, Height = 300 })
.SetTitle(new Title { Text = Title })
.SetSubtitle(new Subtitle { Text = SubTitle })
.SetXAxis(new XAxis { Categories = Categories })
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle { Text = YAxisTitle },
Labels = new YAxisLabels
{
Formatter = #"function() { return this.value +' " + YAxisLabel + "';}"
}
})
.SetLegend(new Legend
{
Layout = Layouts.Vertical,
VerticalAlign = VerticalAligns.Top,
Align = HorizontalAligns.Right,
Shadow = true,
BackgroundColor = ColorTranslator.FromHtml("#FFFFFF"),
Floating = true
})
.SetTooltip(new Tooltip { Formatter = #"function() { return ''+ this.x +' - '+ this.y +' " + ToolTipFormat + "'; }" })
.SetPlotOptions(new PlotOptions
{
Column = new PlotOptionsColumn
{
PointPadding = 0.2,
BorderWidth = 0
}
})
.SetSeries(Series);
return chart;
}
I can set same tooltipFormat for every series with following line:
.SetTooltip(new Tooltip { Formatter = #"function() { return ''+ this.x +' - '+ this.y +' " + ToolTipFormat + "'; }" })
Above code output : date - value tooltipFormat
But I want to show different format for each series. Why do I want this, Because I want to show different data that has different unit, for example:
value[0] = 220 V //Volt
value[1] = 5 A //Ampere
...
value[15] = 1200 kW //Kilowatt
there are a lot of example about this topic but, these examples only change text. My data views like this:
NAME VALUE UNIT
Volt 220 V
Ampere 5 A
....
I want to change tooltipFormat for each series dynamicly. I want to add UNIT field dynamicly. How can I do this?
Thanks.
You can add custom attribute in series object:
series:{name:'series1',unit:'%'}
and can access it in tooltip formatter function:
this.series.options.unit
You can do this directly in a series:
http://api.highcharts.com/highcharts#plotOptions.series.tooltip.valueSuffix
For example, this is a series:
series: [{
data: [10, 20, 30],
type: "line",
name: "Percentage",
tooltip: { valueSuffix: "%", }
},]
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'
}
};
I'd like to make stacked&grouped histograms using HighCharts and ASP.NET MVC3.
I found this example on HighCharts' site: http://www.highcharts.com/demo/column-stacked-and-grouped
I would use JSonResult in my controller.
In particular, in above example, graph series are pre-defined in javascript, while I would dynamically create them with JSON.
With DonNet.Highcharts you can easily create Highcharts only on the server side. There is example with the stacked and grouped column. Here is the server side code:
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetTitle(new Title { Text = "Total fruit consumtion, grouped by gender" })
.SetXAxis(new XAxis { Categories = new[] { "Apples", "Oranges", "Pears", "Grapes", "Bananas" } })
.SetYAxis(new YAxis
{
AllowDecimals = false,
Min = 0,
Title = new YAxisTitle { Text = "Number of fruits" }
})
.SetTooltip(new Tooltip { Formatter = "TooltipFormatter" })
.SetPlotOptions(new PlotOptions { Column = new PlotOptionsColumn { Stacking = Stackings.Normal } })
.SetSeries(new[]
{
new Series
{
Name = "John",
Data = new Data(new object[] { 5, 3, 4, 7, 2 }),
Stack = "male"
},
new Series
{
Name = "Joe",
Data = new Data(new object[] { 3, 4, 4, 2, 5 }),
Stack = "male"
},
new Series
{
Name = "Jane",
Data = new Data(new object[] { 2, 5, 6, 2, 1 }),
Stack = "female"
},
new Series
{
Name = "Janet",
Data = new Data(new object[] { 3, 0, 4, 4, 3 }),
Stack = "female"
}
});
You can pass the data as you like.