i am trying to put bootstrap font icons in my highchart x-axis labels, i have put that in a fiddle, to that you can see it,
http://jsfiddle.net/sanjaybathre/cJRMx/
i am using .net api of highchart code is:
public static string SocialBarStats()
{
Highcharts chart = new Highcharts("chart_SocialBarStats")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Bar })
.SetTitle(new Title { Text = "PAGEVIEWS PER VISIT" })
.SetXAxis(new XAxis
{
Categories = new[] { "<i class=\"icon-facebook\"></i>", "<i class=\"icon-facebook\"></i>",
"<i class=\"icon-facebook\"></i>", "<i class=\"icon-facebook\"></i>", "<i class=\"icon-facebook\"></i>" },
Title = new XAxisTitle { Text = string.Empty }
})
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle
{
Text = "",
Align = AxisTitleAligns.High
}
})
.SetTooltip(new Tooltip { Formatter = "function() { return ''+ this.series.name +': '+ this.y +' millions'; }" })
.SetPlotOptions(new PlotOptions
{
Bar = new PlotOptionsBar
{
DataLabels = new PlotOptionsBarDataLabels { Enabled = true }
}
})
.SetLegend(new Legend
{
Enabled = false
})
.SetCredits(new Credits { Enabled = false })
.SetSeries(new[]
{
new Series { Name = "Facebook", Data = new Data(new object[] { 2.5 }), Color = System.Drawing.Color.FromName("'#4c66a4'")},
new Series { Name = "Pinterest", Data = new Data(new object[] { 1.2 }), Color = System.Drawing.Color.FromName("'#cc181e'") },
new Series { Name = "Youtube", Data = new Data(new object[] { 1.8 }), Color = System.Drawing.Color.FromName("'#a825a9'") },
new Series { Name = "Twitter", Data = new Data(new object[] { 2.3 }), Color = System.Drawing.Color.FromName("'#129fca'") },
new Series { Name = "Google Plus", Data = new Data(new object[] { 2.9 }), Color = System.Drawing.Color.FromName("'#00933B'") }
});
return chart.ToHtmlString();
}
You can use a custom HTML formatter with useHTML and apply the according image based on the element value.
Code:
xAxis: {
categories: ['Google Plus', 'Twitter', 'Youtube', 'Pinterest', 'Facebook'],
title: {
text: ''
},
labels: {
useHTML: true,
formatter: function () {
return {
'Google Plus': '<i class="icon-google-plus"></i>',
'Twitter': '<i class="icon-twitter"></i>',
'Facebook': '<i class="icon-facebook"></i>',
'Pinterest': '<i class="icon-pinterest"></i>',
'Youtube': '<i class="icon-youtube"></i>'
}[this.value];
}
}
},
Demo: http://jsfiddle.net/IrvinDominin/XB7Nw/
You need to set useHTML as true, and add image in the labels formatter.
xAxis: {
labels: {
useHTML:true,
formatter:function() {
return '<img src="http://www.highcharts.com/demo/gfx/snow.png" />' + this.value;
}
}
},
Example: http://jsfiddle.net/7yJf6/
Related
I am new to .NET and using dotnet highcharts in MVC. My task is when clicked on a graph I should display the table with related data based on xaxis value clicked. When clicked on the graph I want to get the x-axis value that is selected and pass this value to the view. How can I do this? Can I get that value from Formatter? How can I add click event to this?
Viewcode:
#model DotNet.Highcharts.Highcharts
#(Model)
Controller code:
public ActionResult CreateSeverityChartVM(string s1, string s2, string s3, string s4, string s5)
{
string select = "";
List<object> series = new List<object>();
series.Add(new DotNet.Highcharts.Options.Point
{
Name = "Severity5",
Y = Convert.ToInt32(s5),
Sliced = true,
Color = ColorTranslator.FromHtml("#FF0000")
});
series.Add(new DotNet.Highcharts.Options.Point
{
Name = "Severity4",
Y = Convert.ToInt32(s4),
Sliced = true,
Color = ColorTranslator.FromHtml("#FF6666")
});
series.Add(new DotNet.Highcharts.Options.Point
{
Name = "Severity3",
Y = Convert.ToInt32(s3),
Sliced = true,
Color = ColorTranslator.FromHtml("#FF3333")
});
series.Add(new DotNet.Highcharts.Options.Point
{
Name = "Severity2",
Y = Convert.ToInt32(s2),
Sliced = true,
Color = ColorTranslator.FromHtml("#FF9999")
});
series.Add(new DotNet.Highcharts.Options.Point
{
Name = "Severity1",
Y = Convert.ToInt32(s1),
Sliced = true,
Color = ColorTranslator.FromHtml("#FFCCCC")
});
string[] myCs = { "Level 5", "Level 4", "Level 3", "Level 2", "Level 1" };
Highcharts chart = new Highcharts("Severities")
.SetTitle(new Title() { Text = "" })
.SetXAxis(new XAxis
{
Categories = myCs
})
.SetPlotOptions(new PlotOptions
{
Column = new PlotOptionsColumn
{
AllowPointSelect = true,
Cursor = Cursors.Pointer,
ShowInLegend = true,
DataLabels = new PlotOptionsColumnDataLabels
{
Color = ColorTranslator.FromHtml("#000000"),
Formatter = "function() { return this.y;}",
},
}
})
.SetSeries(new Series
{
Type = ChartTypes.Column,
Name = "Severity Count",
Data = new Data(series.ToArray())
});
return PartialView("_ChartPartial", chart);
}
You can use chart.events.click event. It fires when clicking on the plot background. Information on the clicked spot can be found through event.xAxis and event.yAxis. Check the demo in pure js.
Code:
// create the chart
Highcharts.chart('container', {
chart: {
events: {
click: function(event) {
var label = this.renderer.label(
'x: ' + Highcharts.numberFormat(event.xAxis[0].value, 2) + ', y: ' + Highcharts.numberFormat(event.yAxis[0].value, 2),
event.xAxis[0].axis.toPixels(event.xAxis[0].value),
event.yAxis[0].axis.toPixels(event.yAxis[0].value)
)
.attr({
fill: Highcharts.getOptions().colors[0],
padding: 10,
r: 5,
zIndex: 8
})
.css({
color: '#FFFFFF'
})
.add();
setTimeout(function() {
label.fadeOut();
}, 1000);
}
}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px"></div>
Demo:
https://jsfiddle.net/BlackLabel/dbqpou4v/
JS API reference:
https://api.highcharts.com/highcharts/chart.events.click
.NET API reference:
http://dotnet.highcharts.com/Help/Highcharts/html/class_highsoft_1_1_web_1_1_mvc_1_1_charts_1_1_chart_events.html#a87a3128090852777824e4118123a2579
We should add click in SetPlotOptions. when we click on graph it is calling showdetails function. showdetails is a java function defined in the view(index).It worked for me.
.SetPlotOptions(new PlotOptions
{
Column = new PlotOptionsColumn
{
AllowPointSelect = true,
Cursor = Cursors.Pointer,
ShowInLegend = true,
DataLabels = new PlotOptionsColumnDataLabels
{
Color = ColorTranslator.FromHtml("#000000"),
Formatter = "function() { return this.y;}"
},
Point = new PlotOptionsColumnPoint() { Events = new PlotOptionsColumnPointEvents() { Click = "function(e) { showDetails(this.name); }" } }
}
})
I am using Highsoft.Web.Mvc.Charts .I have a PIE chart and its drilled down NOW I want to open a column chart after clicking on any point of drilled down pie chart. My code in view is
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/drilldown.js"></script>
#using Highsoft.Web.Mvc.Charts
#{
Highcharts chart2 = new Highcharts
{
Title = new Title
{
Text = "Total Pages Accessed by Teams"
},
Subtitle = new Subtitle
{
Text = "RiO."
},
XAxis = new List<XAxis>
{
new XAxis
{
Type = XAxisType.Category
}
},
YAxis = new List<YAxis>
{
new YAxis
{
Title = new YAxisTitle
{
Text = "Total percent market share"
}
}
},
Legend = new Legend
{
Enabled = false
},
Tooltip = new Tooltip
{
HeaderFormat = "<span style='font-size:11px'>{series.name}</span><br>",
PointFormat = "<span style=\"color:{point.color}\">{point.name}</span>: <b>{point.y}</b> Pages<br/>"
},
PlotOptions = new PlotOptions
{
Series = new PlotOptionsSeries
{
DataLabels = new PlotOptionsSeriesDataLabels
{
Enabled = true,
Format = "{point.name}: {point.y}"
},
Cursor = PlotOptionsSeriesCursor.Pointer,
Point = new PlotOptionsSeriesPoint
{
Events = new PlotOptionsSeriesPointEvents
{
}
}
}
},
Series = new List<Series>
{
new PieSeries
{
Name = "Teams data",
Data = #ViewData["pieData"] as List<PieSeriesData>
}
},
Drilldown = new Drilldown
{
Series = #ViewData["Series"] as List<Series>
}
};
}
#Html.Highsoft().GetHighcharts(chart2, "chart2")
Thanks in advance for any help.
Got the answer as thanks to http://jsfiddle.net/nagoba/V4q69/1/
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
},
point: {
events: {
click: function () {
if (this.x != "" && this.x != null)
drawColumnGraph(this.name)
}
}
}
}
}
},
here was my code
var dates = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["ph"]));
$('#StartDate').datepicker({
format: 'dd-M-yyyy',
autoclose: true,
beforeShowDay: function (date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
return [true, 'ui-state-highlight'];
}
}
return [true];
}
});
i had the date 18th was outlined in yellow.
how can i change it into red solid?
You could do this via CSS:
.ui-state-highlight {
border-color: red;
}
An example:
var dtNow = new Date();
function addDays(d) {
return d * 86400000;
}
function showMyDate(d) {
return d.getDate() + (d.getMonth() + 1) + d.getFullYear();
}
var dates = [
new Date(dtNow.getTime() + addDays(5)),
new Date(dtNow.getTime() + addDays(10)),
new Date(dtNow.getTime() + addDays(12)),
];
$(function() {
$("#datepicker").datepicker({
format: 'dd-M-yyyy',
autoclose: true,
beforeShowDay: function(date) {
var status = [];
$.each(dates, function(key, myDate) {
if (showMyDate(myDate) === showMyDate(date)) {
status = [true, 'ui-state-highlight highlight-red', ''];
} else {
status = [true, '', ''];
}
});
return status;
}
});
});
In this example, I have added two classes: ui-state-highlight and highlight-red. This way I can directly change just the ones that need to be red.
CSS
td.ui-state-highlight.highlight-red {
border-color: red;
}
Working Example: https://jsfiddle.net/Twisty/6fapkykr/
I am trying to display some more data in highcharts bubble chart tooltip with no success. How can I access this.point.comments inside the tooltip formatter?
The bubble chart I am using has datetime as x-axis.
$('#chart-bubble').highcharts({
chart: {
type: 'bubble',
zoomType: 'xy',
plotBorderWidth: 1
},
title: {
text: 'Risk & Profit Vs Date'
},
tooltip: {
useHTML: true,
formatter: function(){
var expectedProfit = '';
if( this.point.z !== 'none' )
{
expectedProfit = formatExpectedProfit(this.point.z);
}
var tooltip = '<table class="table table-bordered" style="width: 300px;"><tbody><tr><td colspan="2"><h5>'+this.series.name.substr(0,75)+'...</h5></td></tr>' +
'<tr><td>Risk:</td><td>'+this.y+'</td></tr>';
if( expectedProfit !== '' )
{
tooltip += '<tr><td>Profit:</td><td>'+expectedProfit+'</td></tr>';
}
else
{
tooltip += '<tr><td>Comments:</td><td>'+this.point.comments+'</td></tr>';
}
tooltip += '</tbody></table>';
return tooltip;
},
followPointer: false
},
rangeSelector: {
enabled:true
},
xAxis:{
type: 'datetime',
dateTimeLabelFormats: {
day: '%e of %b'
}
},
yAxis: {
title: {
text: 'Ri'
}
},
series: prepareData(res.bubble)
});
Here is the prepareData function:
function prepareData(data)
{
for( var i in data )
{
var item = data[i];
for( var k in item.data )
{
var itemData = item.data[k];
if( itemData[0] )
{
var split = itemData[0].split("-");
var y = split[0];
var m = split[1]-1;
var d = split[2];
itemData[0] = Date.UTC(y,m,d);
item.data[k] = itemData;
}
}
data[i] = item;
}
return data;
}
And the res.bubble json returned from PHP:
$list = array();
$list[] = array('name'=>'project 1','color'=>'#FF0000','data'=>array(new \DateTime(),20,'none'),'pointInterval'=>86400000,'comments'=>'this is a comment');
//.... repeating by adding some more elements to this array
You can access all additional properties via point.options[/* property */.
Highcharts.chart('container', {
chart: {
type: 'bubble',
},
tooltip: {
formatter: function () {
return this.point.options.comments[0];
}
},
series: [{
data: [
{ x: 95, y: 95, z: 13.8, name: 'BE', comments: ['this is a comment'] },
]
}]
});
example: http://jsfiddle.net/yd1vjfmp/
I have Created JqGrid for loading some records like below.
<script type="text/javascript">
$(document).ready(function () {
$('#jqgRequests').jqGrid({
defaults: {
recordtext: "View {0} - {1} of {2}",
emptyrecords: "No Request Found",
loadtext: "Loading...",
pgtext: "Page {0} of {1}"
},
//url from wich data should be requested
url: '#Url.Action("LoadRequest")',
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['Is Approved','Requestor', 'Request Type', 'Request Date', 'Approved Date', 'Package','Comments','RequestID', '','',''],
//columns model
colModel: [
{ name: 'IsApproved',
formatter: function (cellvalue, options, rowObject) {
var status = rowObject[0];
if (status == 1) {
return '<input type="checkbox" name="approval" checked disabled="disabled">';
}
else if(status==2) {
return '<img src="#Url.Content("~/Content/images/reject.jpg")"></img>';
}
else{
return '<input type="checkbox" name="approval" disabled="disabled" >';
}
},sortable:false, align: 'center', width: 80, index: 'subColumn'
},
{ name: 'Requestor', index: 'Requestor', width: 170, align: 'left' },
{ name: 'Request Type', index: 'RequestType', width: 90, align: 'left' },
{ name: 'RequestDate', index: 'RequestDate', formatter: 'date', formatoptions: { srcformat: 'FullDateTime', newformat: 'd/m/Y g:i:s A' }, width: 120, align: 'left' },
{ name: 'ApprovedDate', index: 'ApprovedDate', formatter: 'date', formatoptions: { srcformat: 'FullDateTime', newformat: 'd/m/Y g:i:s A' }, width: 120, align: 'left' },
{ name: 'Package', index: 'Package', width: 150, align: 'left' },
{ name: 'Comments', index: 'Comments', width: 300, align: 'left' },
{ name: 'RequestID', index: 'RequestID', width: 1, align: 'left',hidden:true },
{ name: 'Approve',
formatter: function (cellvalue, options, rowObject) {
var status = rowObject[0];
if(status==1)
{
return '#Html.ActionLink("Approve", null, null, new { #style = "color:blue;font-weight:bold;", onclick = "return WarningPopup('Already approved');", href = "#" })';
}
else{
var x = '#Html.ActionLink("Approve", null, null, new { #style = "color:Blue;font-weight:bold;", onclick = "return ConfirmPopup('myId');", href = "#" })';
// var x = '#Html.ActionLink("Approve", "Approve", "Dashboard", new { requestId = "myId" }, new { #style = "color:Blue;font-weight:bold;", onclick = "return confirm('Are you sure to approve this request?');" })';
return x.replace("myId",rowObject[7]);
}
},sortable:false, align: 'left', width: 45
},
{ name: 'Reject',
formatter: function (cellvalue, options, rowObject) {
var status = rowObject[0];
if(status==2)
{
return '#Html.ActionLink("Reject", null, null, new { #style = "color:blue;font-weight:bold;", onclick = "return WarningPopup('Already rejected');", href = "#" })';
}
else{
var x = '#Html.ActionLink("Reject", null, null, new { #style = "color:Blue;font-weight:bold;", onclick = "return Rejectpopup('myId');", href = "#" })';
// var x = '#Html.ActionLink("Reject", "Reject", "Dashboard", new { requestId = "myId" }, new { #style = "color:Blue;font-weight:bold;", onclick = "return confirm('Are you sure to reject this request?');" })';
return x.replace("myId",rowObject[7]);
}
},sortable:false, align: 'left', width: 60
},
{ name: 'More',
formatter: function (cellvalue, options, rowObject) {
// var x = "<a class='btnMore' onclick='GetDetail('myId');' style = 'color:blue;font-weight:bold;' href='#'>More Detail</a>"
var x='#Html.ActionLink("Detail", null, null, new { #style = "color:blue;font-weight:bold;", onclick = "return GetDetail('myId');", href = "#" })';
return x.replace("myId",rowObject[7]);
},sortable:false, align: 'left', width: 80
}
],
//pager for grid
pager: $('#jqgpRequests'),
//number of rows per page
rowNum: 25,
//initial sorting column
sortname: 'RequestID',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
//grid height
height: '100%'
});
});
</script>
Action Result
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult LoadRequest(JqGridRequest request)
{
int totalRecords = _dashboardRepository.RequestCount;
var response = new JqGridResponse()
{
TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
PageIndex = request.PageIndex,
TotalRecordsCount = totalRecords
};
const string subColumn = "";
foreach (var dashboard in _dashboardRepository.LoadAllRequests(request.SortingName, request.SortingOrder.ToString(), request.PageIndex, request.RecordsCount))
{
response.Records.Add(new JqGridRecord(dashboard.RequestID.ToString(), new List<object>()
{
dashboard.IsApproved,
dashboard.Requestor,
dashboard.RequestType,
dashboard.RequestDate,
dashboard.ApprovedDate,
dashboard.Package,
dashboard.Comments,
dashboard.RequestID
}));
}
return new JqGridJsonResult { Data = response };
}
This jqGrid load when the page load. Also i have added a dropdown list for filtering. For this i need to post some parameters for the JqGridRequest class . How can i possible this?
Assuming that your dropdown id is ddlFilter you can write the JavaScript change event handler like this:
$('#ddlFilter').on('change', function(e) {
$('#jqgRequests').setGridParam({ postData: { FilterValue: $(this).val(); } }).trigger('reloadGrid', [{ page: 1 }]);
});
On server side you can create following view model for handling the post data:
public class PostDataViewModel
{
public string FilterValue { get; set; }
}
And add it as one more parameter to your action:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult LoadRequest(JqGridRequest request, PostDataViewModel postData)
{
...
}
Unless there is some specifc requirement or edge case you haven't describe in your question this should do the trick.
If I understand you correct you can follow the suggestion from the old answer.
If you have for example <select id="mySelect">...</select> on the page you can use jqGrid option
postData: {
myFilter: function () {
return $("#mySelect option:selected").val();
}
}
to send the value of the select box together with other standard jqGrid parameters (see JqGridRequest). If you want additionally to reload the grid after every changes of the select you can use .trigger("reloadGrid"). You need just set change and keyup event handler and calls .trigger("reloadGrid") it it require. See the answer for more code example.