I have created a horizontal bar chart. I have generated the data for the bar chart from the database in the code behind.
I have two questions regarding the bar chart:
The bar charts are displaying but few of them are overlapping. I have tried setting "barPadding" and "barMargin" but that doesn't work.
I want to display label against each bar chart stating what each bar represents. These labels are retrieved from the database in code behind and stored in string array. That is against each bar in the bar chart I want to display label like "Accounts", "Telecommunication" etc. These labels are in the array retrieved from database in code behind.
Any inputs on above queries would be much appreciated.
The following is the JQPlot Script
<script type="text/javascript">
function RunTest() {
$.jqplot.config.enablePlugins = true;
<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();%>
var industryName = <%= serializer.Serialize(arrIndustryName) %>
industryPostings = <%= serializer.Serialize(arrIndustryPostings)%>
plot = $.jqplot('dispStats', [industryPostings], {
captureRightClick: true,
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
showAngel: 135,
rendererOptions: {
barDirection: 'horizontal',
barMargin: 200,
barPadding: 500,
barWidth: 10,
highlightMouseDown: true
},
pointLabels: { show: true, formatString: '%d' }
},
legend: {
show: true,
location: 'e',
placement: 'outside'
},
axes: {
yaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
return false;
}
</script>
//asp.net button control to invoke code behind code and run the bar chart script
<asp:Button ID="btnTrends" runat="server" Text="Get Data" OnClick="GetPostingStatistics"
style="margin-right:10px"/>
<asp:Button ID="test" runat="server" Text="Show Trend" OnClientClick="return RunTest()" />
The following is the Code Behind Code
protected void GetPostingStatistics(object sender, EventArgs e)
{
string strFromDate = txtFromDate.Text;
string strToDate = txtToDate.Text;
switch (ddlTrend.SelectedValue)
{
case "Industries":
{
//Code for Sql Connection
sql = "select Value from mpats_FieldValue where FieldID =15";
cmd = new SqlCommand(sql, conn);
adapter = new SqlDataAdapter(cmd);
postingRecords = new DataSet();
adapter.Fill(postingRecords);
List<string> industryNames = new List<string>();
// Code for retrieving labels against each bar from database
foreach (DataRow name in postingRecords.Tables[0].Rows)
{
industryNames.Add(name.Field<string>("Value"));
}
int[] numberOfPostings = new int[industryNames.Count];
for (int i = 0; i < industryNames.Count; i++)
{
sql = "select count(p.PostingId) as PostingsCount from
mpats_AdvertPosting p left join mpats_Advert a on p.AdvertID =
a.AdvertID " +
"where p.PostingStatusID between 400 and 451 " +
"and a.Industry = #Industry";
cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Industry", industryNames[i]);
adapter = new SqlDataAdapter(cmd);
postingRecords = new DataSet();
adapter.Fill(postingRecords);
numberOfPostings[i] = Convert.ToInt32(postingRecords.Tables
[0].Rows[0]
["PostingsCount"]);
}
arrIndustryName = industryNames.ToArray();
arrIndustryPostings =
numberOfPostings;
}
conn.Close();
break;
}
default:
{
break;
}
}
}
Thanks
Shwetha
Related
I'm working with a Kendo treelist widget, and disappointed to see there's no rowTemplate option as there is on the Kendo grid.
I see a columnTemplate option (i.e. http://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#configuration-columns.template ), but this will affect the entire column.
However, I need to drill into each cell value and set a css color property based on a ratio ( i.e. If value/benchmark < .2, assign <span style='color:red;'> , but my color value is dynamic.
There's a dataBound: and dataBinding: event on the treelist, but I'm still trying to figure out how to intercept each cell value and set the color once I've done my calculation.
var treeOptions = {
dataSource: ds,
columns: colDefs,
selectable: true,
scrollable: true,
resizable: true,
reorderable: true,
height: 320,
change: function (e) {
// push selected dataItem
var selectedRow = this.select();
var row = this.dataItem(selectedRow);
},
dataBound: function (e) {
console.log("dataBinding");
var ds = e.sender.dataSource.data();
var rows = e.sender.table.find("tr");
}
};
and this is where I'm building out the `colDefs' object (column definitions):
function parseHeatMapColumns(data, dimId) {
// Creates the Column Headers of the heatmap treelist.
// typeId=0 is 1st Dimension; typeId=1 is 2nd Dimension
var column = [];
column.push({
"field": "field0",
"title": "Dimension",
headerAttributes: { style: "font-weight:" + 'bold' + ";" },
attributes : { style: "font-weight: bold;" }
});
var colIdx = 1; // start at column 1 to build col headers for the 2nd dimension grouping
_.each(data, function (item) {
if (item.typeId == dimId) {
// Dimension values are duplicated, so push unique values (i.e. trade types may have dupes, whereas a BkgLocation may not).
var found = _.find(column, { field0: item.field0 });
if (found == undefined) {
column.push({
field: "field2",
title: item.field0,
headerAttributes: {
style: "font-weight:" + 'bold'
}
,template: "<span style='color:red;'>#: field2 #</span>"
});
colIdx++;
}
}
});
return column;
}
**** UPDATE ****
In order to embed some logic within the template :
function configureHeatMapColumnDefs(jsonData, cols, model) {
var colDef = '';
var dimId = 0;
var colorProp;
var columns = kendoGridService.parseHeatMapColumns(jsonData, dimId);
// iterate columns and set color property; NB: columns[0] is the left-most "Dimension" column, so we start from i=1.
for (var i = 1; i <= columns.length-1; i++) {
columns[i]['template'] = function (data) {
var color = 'black';
if (data.field2 < 1000) {
color = 'red';
}
else if (data.field2 < 5000) {
color = 'green';
}
return "<span style='color:" + color + ";'>" + data.field2 + "</span>";
};
}
return columns;
}
Advice is appreciated.
Thanks,
Bob
In the databound event you can iterate through the rows. For each row you can get the dataItem associated with it using the dataitem() method (http://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#methods-dataItem)
Once you have the dataitem, calculate your ration and if the row meets the criteria for color, change the cell DOM element:
dataBound: function (e) {
var that = e.sender;
var rows = e.sender.table.find("tr");
rows.each(function(idx, row){
var dataItem = that.dataItem(row);
var ageCell = $(row).find("td").eq(2);
if (dataItem.Age > 30) {
//mark in red
var ageText = ageCell.text();
ageCell.html('<span style="color:red;">' + ageText + '</span>');
}
}
DEMO
UPDATE: you can also do this with a template:
$("#treelist").kendoTreeList({
dataSource: dataSource,
height: 540,
selectable: true,
columns: [
{ field: "Position"},
{ field: "Name" },
{ field: "Age",
template: "# if ( data.Age > 30 ) { #<span style='color:red;'> #= data.Age # </span> #}else{# #= data.Age # #}#"
}
],
});
DEMO
How can statistical data be shown in a chart format using the Razor Chart Helper of MVC ?
When you want to display your data in graphical form, you can use Chart helper. The Chart helper can render an image that displays data in a variety of chart types.
You can create a view having razor code for chart as follows(lets say its MyChart.cshtml).
Bar chart from Array with theam
#{
var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Green)
.AddTitle("Chart Title")
.AddSeries(
name: "ChartTitle",
xValue: new[] { "Col1", "Col2", "Col3", "Col4", "Col5" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
Pie chart from Array
#{
var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Green)
.AddTitle("Chart Title")
.AddSeries(
name: "ChartTitle",
chartType: "Pie",
xValue: new[] { "Col1", "Col2", "Col3", "Col4", "Col5" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
Pie chart from Array with theam
#{
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.AddSeries(
name: "ChartTitle",
chartType: "Pie",
xValue: new[] { "Col1", "Col2", "Col3", "Col4", "Col5" },
yValues: new[] { "2", "6", "4", "5", "3" })
.Write();
}
Bar Chart Using DB Query
#{
var db = Database.Open("DBName");
var data = db.Query("SELECT Col1, Col2 FROM Table");
var myChart = new Chart(width: 600, height: 400)
.AddTitle("Chart Title")
.DataBindTable(dataSource: data, xField: "Col1")
.Write();
}
You can use these chart views/PartialView where ever required as a src of image.
ex.
<html>
<body>
<img src="MyChart.cshtml" />
<!-- or <img src='#Url.Action("Controler","ActionNameOfChartRenderingView")' />-->
<body>
<html>
Chart Theams
Vanilla Displays red columns on a white background.
Blue Displays blue columns on a blue gradient background.
Green Displays blue columns on a green gradient background.
Yellow Displays orange columns on a yellow gradient background.
Vanilla3D Displays 3-D red columns on a white background.
SeriesChartType enumeration supports the following:
Area
Bar
BoxPlot
Bubble
Candlestick
Column
Doughnut
ErrorBar
FastLine
FastPoint
Funnel
Kagi
Line
Pie
Point
PointAndFigure
Polar
Pyramid
Radar
Range
RangeBar
RangeColumn
Renko
Spline
SplineArea
SplineRange
StackedArea
StackedArea100
StackedBar
StackedBar100
StackedColumn
StackedColumn100
StepLine
Stock
ThreeLineBreak
This is the list of names that you can pass, as strings, to the Chart helper in a Razor page.
This is Helper
namespace System.Web.Helpers
{
public class Chart
{
public Chart(int width, int height, string template = null, string templatePath = null);
public string FileName { get; }
public int Height { get; }
public int Width { get; }
public Chart AddLegend(string title = null, string name = null);
public Chart AddSeries(string name = null, string chartType = "Column", string chartArea = null, string axisLabel = null, string legend = null, int markerStep = 1, IEnumerable xValue = null, string xField = null, IEnumerable yValues = null, string yFields = null);
public Chart AddTitle(string text = null, string name = null);
public Chart DataBindCrossTable(IEnumerable dataSource, string groupByField, string xField, string yFields, string otherFields = null, string pointSortOrder = "Ascending");
public Chart DataBindTable(IEnumerable dataSource, string xField = null);
public byte[] GetBytes(string format = "jpeg");
public static Chart GetFromCache(string key);
public Chart Save(string path, string format = "jpeg");
public string SaveToCache(string key = null, int minutesToCache = 20, bool slidingExpiration = true);
public Chart SaveXml(string path);
public Chart SetXAxis(string title = "", double min = 0, double max = 0.0 / 0.0);
public Chart SetYAxis(string title = "", double min = 0, double max = 0.0 / 0.0);
public WebImage ToWebImage(string format = "jpeg");
public Chart Write(string format = "jpeg");
public static Chart WriteFromCache(string key, string format = "jpeg");
}
}
example ...
Controler
namespace MVC3ChartTest.Controllers
{
public class ChartsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult BasicChart()
{
return View();
}
public ActionResult BasicChartWithMasterPage()
{
return View();
}
}
}
non-strongly-typed view
#model dynamic
#{
View.Title = "BasicChart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Basic Chart</h2>
<p>
#{
var key = new Chart(width: 600, height: 400)
.AddTitle("Staff Mobility")
.AddSeries(
name: "Employee",
xValue: new[] { "Jan", "Feb", "Mar", "Api", "May", "Jun", "Jul", "Aug", "Sep"},
yValues: new[] { "2", "6", "4", "5", "3","4","9","2","5"}
)
.Write();
}
</p>
BasicChartWithMasterPage
#model dynamic
#{
View.Title = "BasicChartWithMasterPage";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>BasicChartWithMasterPage</h2>
<p><img src="BasicChart" /> </p>
Example 2
Model
//other omitted...
using System.Collections;
using System.Web.Helpers;
namespace MVC3ChartTest.Models
{
internal class PieChartData
{
public string Title { get; set; }
public Category_Sales_for_1997[] Data { get; set; }
}
public class NorthModel
{
NorthwindEntities db = new NorthwindEntities();
List<Category_Sales_for_1997> pieData;
public Chart PieChart
{
get
{
return BuildServerPieChart();
}
}
public NorthModel()
{
pieData = db.Category_Sales_for_1997.ToList<Category_Sales_for_1997>();
}
//other omitted...
Functions to return chart
private Chart BuildServerPieChart()
{
var data = new PieChartData
{
Title = "Total: " + (from y in pieData select y.CategorySales).Sum().ToString(),
Data = (from x in pieData orderby x.CategoryName descending select x).ToArray(),
};
return BindChartData(data);
}
private Chart BindChartData(PieChartData data)
{
Chart chart = new Chart(
width: 400,
height: 300,
template: ChartTheme.Green);
chart.AddTitle(data.Title);
chart.AddLegend(title: "Lengend Title", name: null);
ArrayList x_ValueArray = new ArrayList();
ArrayList y_ValuesArray = new ArrayList();
for (int i = 0; i < data.Data.Length; i++)
{
x_ValueArray.Add(data.Data[i].CategoryName);
y_ValuesArray.Add(data.Data[i].CategorySales);
}
chart.AddSeries(
name: "Employee",
chartType: "Pie",
axisLabel: "Name",
xValue: x_ValueArray,
yValues: y_ValuesArray);
return chart;
}
Controller Action
public ActionResult Index()
{
NorthModel model = new NorthModel();
return View(model);
}
View
#model MVC3ChartTest.Models.NorthModel
#{
View.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div>
#{Model.PieChart.Write();}
</div>
I have a sample fiddle here in which the Google visualization Category Filter control is created as,
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnIndex': 0,
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var regionPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnIndex': 1,
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var cityPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control3',
'options': {
'filterColumnIndex': 2,
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
Here We can select the filter in any combination. But, If I directly select Albany in CityPicker control then, how can I get its parent's values (ie, The value USA from countryPicker and the value New York from regionPicker) in which that particular city belongs to?
You can use a statechange event handler to get the current city, and then filter the DataTable by city to get the region and country combo(s) that correspond to that city. Here's an example:
google.visualization.events.addListener(cityPicker, 'statechange', function () {
var state = cityPicker.getState();
if (state.selectedValues.length) {
// there is a selected city
// since you set allowMultiple to false, there can be only one, so it is safe to do this:
var city = state.selectedValues[0];
var rows = data.getFilteredRows([{column: 2, value: city}]);
// parse the rows for all country/region/state combos
var regionsCountries = [];
var comboChecker = {};
for (var i = 0; i < rows.length; i++) {
var country = data.getValue(rows[i], 0);
var region = data.getValue(rows[i], 1);
// the comboChecker makes sure we don't add a region/country combo more than once to the data set
if (!comboChecker[region + country]) {
comboChecker[region + country] = true;
regionsCountries.push({region: region, country: country});
}
}
// do something with regionsCountries
}
});
See working example here: http://jsfiddle.net/asgallant/KLhD3/1/
I am trying a method to bind data to the Pie chart
Public ActionResult Charts
{
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { PlotShadow = false })
.SetTitle(new Title { Text = "Browser market shares at a specific website, 2010" })
.SetTooltip(new Tooltip { Formatter = "function() { return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; }" })
.SetPlotOptions(new PlotOptions
{
Pie = new PlotOptionsPie
{
AllowPointSelect = true,
Cursor = Cursors.Pointer,
DataLabels = new PlotOptionsPieDataLabels
{
Color = ColorTranslator.FromHtml("#000000"),
ConnectorColor = ColorTranslator.FromHtml("#000000"),
Formatter = "function() { return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; }"
}
}
})
.SetSeries(new Series
{
Type = ChartTypes.Pie,
Name = "Browser share",
Data = new Data(new object[]
{
new object[] { "Firefox", 45.0 },
new object[] { "IE", 26.8 },
new DotNet.Highcharts.Options.Point
{
Name = "Chrome",
Y = 12.8,
Sliced = true,
Selected = true
},
new object[] { "Safari", 8.5 },
new object[] { "Opera", 6.2 },
new object[] { "Others", 0.7 }
})
});
}
}
public JsonResult GetData()
{
int Param1;
Param1 = 1;
var reports = db.ExecuteStoreQuery<ResourceReports>("ResourceReports #EmployeeID", new SqlParameter("#EmployeeID", Param1)).ToList();
return Json(reports, JsonRequestBehavior.AllowGet);
}
i want to replace
.SetSeries(new Series
{
Type = ChartTypes.Pie,
Name = "Browser share",
Data = new Data(new object[]
{
new object[] { "Firefox", 45.0 },
new object[] { "IE", 26.8 },
new DotNet.Highcharts.Options.Point
{
Name = "Chrome",
Y = 12.8,
Sliced = true,
Selected = true
},
new object[] { "Safari", 8.5 },
new object[] { "Opera", 6.2 },
new object[] { "Others", 0.7 }
})
});
}
with my GetData() how can i do this,the Data in .SetSeries should be my returned data in GetData method
It appears you are using Dotnet.Highcharts. You could create a list of Series and a list of Point.
List<Series> mySeries = new List<Series>();
List<Point> myPoints = new List<Point>();
I would loop through each series you need to create and generate the point data like so:
myPoints.Add(new Point {
X = (detailRec.RecordTime - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds,
Y = detailRec.TotalCount
});
Then you could create the series itself using the list of points for its data like so:
mySeries.Add(new Series{
Name = distinctDistrict.Name,
Data = new Data(myPoints.ToArray())
});
Then to set the Series you could use the following statement:
.SetSeries(mySeries.Select(s => new Series {
Name = s.Name,
Data = s.Data
}).ToArray())
If you use the object browser in Visual Studio, you can see the other properties and methods of the Series and Point class. To use the above code you will have to include the the following using statements:
using DotNet.Highcharts;
using DotNet.Highcharts.Enums;
using DotNet.Highcharts.Helpers;
using DotNet.Highcharts.Options;
using Point = DotNet.Highcharts.Options.Point;
Hi I am trying to implement a combined highchart using dotnet highcharts.So I have a column chart+pie chart.
I made List allSeries = new List()for column Chart and List pieSeries = new List()for pie chart.
I dont know how to pass this two series to to the .SetSeries() wich accepts SetSeries(Series series);
or SetSeries(Series[] seriesArray);
public ActionResult Profit()
{
DBContext.Current.Open();
List<RoomType> result = new List<RoomType>();
result = RoomType.Selectcount();
List<Series> allSeries = new List<Series>();
List<Series> pieSeries = new List<Series>();
List<DotNet.Highcharts.Options.Point> puncte = new List<DotNet.Highcharts.Options.Point>();
string[] categories = new[] { "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie" };
object[] pointnum = new object[12];
foreach (var j in result)
{
for (int i = 0; i < pointnum.Length; i++)
{
pointnum[i] = Roomtypereservations.RoomTypeByDate(j.RoomType_ID, i + 1).FirstOrDefault().NumRezervari;
}
allSeries.Add(new Series
{
Type=ChartTypes.Column,
Name = j.Room_Type,
//Data = new Data(myData)
Data = new Data(pointnum.ToArray())
});
pieSeries.Add(new Series
{
Type = ChartTypes.Pie,
Name = "Total rooms",
Data = new Data(puncte.ToArray())
});
puncte.Add(new DotNet.Highcharts.Options.Point
{
Name = j.Room_Type,
Y=13
//Data = new Data(myData)
});
}
Highcharts chart = new Highcharts("chart")
.SetTitle(new Title { Text = "Combination chart" })
.SetTooltip(new Tooltip { Formatter = "function() { return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; }" })
.SetXAxis(new XAxis { Categories =categories} )
.SetTooltip(new Tooltip { Formatter = "TooltipFormatter" })
.AddJavascripFunction("TooltipFormatter",
#"var s;
if (this.point.name) { // the pie chart
s = ''+
this.point.name +': '+ this.y +' fruits';
} else {
s = ''+
this.x +': '+ this.y;
}
return s;")
.SetLabels(new Labels
{
Items = new[]
{
new LabelsItems
{
Html = "Total fruit consumption",
Style = "left: '40px', top: '8px', color: 'black'"
}
}
})
.SetPlotOptions(new PlotOptions
{
Pie = new PlotOptionsPie
{
Center = new[] { "100", "80" },
Size = "100",
ShowInLegend = false,
DataLabels = new PlotOptionsPieDataLabels { Enabled = false }
}
})
.SetSeries(allSeries.Select(s => new Series { Type = s.Type, Name = s.Name, Data = s.Data }).ToArray());
return View(chart);
When i am working with only one series like in my sample
its working:
.SetSeries(allSeries.Select(s => new Series { Type = s.Type, Name = s.Name, Data = s.Data }).ToArray());
how can i pas both pieSeries and all Series to .SetSeries?
You don't need both allSeries and pieSeries. I would get rid of pieSeries. You can assign as many series to your allSeries List as you need and they can be of any type. So change your pieSeries.Add to the following:
allSeries.Add(new Series
{
Type = ChartTypes.Pie,
Name = "Total rooms",
Data = new Data(puncte.ToArray())
})
Then the following statement will work and all of your required Series to the chart:
.SetSeries(allSeries.Select(s => new Series { Type = s.Type, Name = s.Name, Data = s.Data }).ToArray());