I am making a line chart using highchart and i want to try to make different color on it.
Let me show you my current code :
I have 6 arrays:
var xAxes = ['2021-05-05','2021-05-06','2021-05-07','2021-05-08','2021-05-09']
var Min = [2,2,2,2,2]
var Max = [200,200,200,200,200]
var value = [100,134,156,133,26]
var judge = ['OK','NG','OK','OK','NG']
var boxNo = ['Box1','Box1','Box1','Box2','Box2']
And here is my code for creating the chart :
$('#container5').highcharts({
chart: {
type: 'line',
zoomType: 'x'
},
title: {
text: 'Daily IC Log Data'
},
subtitle: {
text: 'Running Date'
},
xAxis: {
tickInterval: 150,
categories: xAxes,
type: 'datetime',
labels: {
enabled: false
}
},
yAxis: {
title: {
text: 'Value'
},
gridLineWidth: 0,
minorGridLineWidth: 0
},
plotOptions: {
series: {
turboThreshold: 1000000
}
},
tooltip: {
shared: true,
headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y} us<br/>'
},
series: [
{
name: 'Value',
data: value,
type: 'spline',
tooltip: {
valueDecimals: 2
}
},
{
name: 'Minimun Std',
data: Min,
color: 'red',
type: 'spline',
line: {
dashStyle: 'longdash'
},
tooltip: {
valueDecimals: 2
}
},
{
name: 'Maximum Std',
data: Max,
type: 'spline',
tooltip: {
valueDecimals: 2
}
}
]
});
From my code above, I want to make differential on my line chart based on boxNo.
The line color on chart should be different based on boxNo. Is it possible?
Any help would be appreciated.
You can create a function to generate zones for a series based on the boxNo array. Example:
var colorsMap = {
Box1: ['blue', 'red', 'black'],
Box2: ['green', 'yellow', 'orange']
};
function getZonesForSeries(seriesIndex) {
var currentZone;
var zones = [];
boxNo.forEach(function(bN, index) {
if (bN !== currentZone) {
currentZone = bN;
if (zones.length) {
zones[zones.length - 1].value = index;
}
zones.push({
color: colorsMap[bN][seriesIndex]
});
}
});
return zones;
}
Live demo: http://jsfiddle.net/BlackLabel/t8hcab7d/
API Reference: https://api.highcharts.com/highcharts/series.line.zones
I'm creating a bar chart in ASP.NET 2.0 using HighCharts JS.
here's how the chart can be do in javascript:
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
});
i have this in c# code-behind:
public string[] Names = new string[] { "Name1", "Name2", "Name3"};
public string[] Data = new string[] { "[1,0,4]", "[5,7,3]", "[2,3,4]"};
How can I used this string[] Names and Data in javascript to change the value of the chart?
Please help I'm stuck in it. :( Thanks!
--EDIT for ARISTOS--
I tried your answer but that doesn't work. Base on your answer this javascript will be the same with what you do. check this:
$(function () {
var seriesTest = "{ name: 'Jane', data: [1, 0, 4] }, { name: 'John', data: [5, 7, 3] }";
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [seriesTest]
});
});
I tried this already but this not work because I think series.data only accepts integer inside its bracket ([]).
I already check DotNet.HighCharts as suggested by KingCronus but this can't be use in asp.net 2.0 framework. :(
On the most simple form, you just need to render them on the correct format.
Here is a simple example that maybe need a few tweeks...
Run this on code behind, maybe on PageLoad
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < 3 ; i++)
sb.AppendFormat("{3}{{name: '{0}',data: {1} }}",
Names[i], Data[i],
i>0 ? "," : "" // this is render the comma "," after the first line
);
ScriptData.Text = sb.ToString();
And place them on the script on the page using a Literal control
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [
<asp:Literan id="ScriptData" Runat="server" EnableViewState="off" />
]
});
});?
Here's what my solution for my problem, in case there would someone need this also.
Here's the JS function:
function LoadChart() {
var Names = <%= this.javaSerial.Serialize(this.Names %>;
var Data = <%= this.javaSerial.Serialize(this.Data %>;
var options = {
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apple', 'Banana', 'Orange']
},
yAxis: {
title: {
text: 'fruit eaten'
}
},
series: [{
name: Names[0],
data: [Data[0]]
}]
};
for (var i=1; i<Names.Length; i++)
{
options.series.push({
name: Names[i],
data: [Data[i]]
});
}
var chart = new Highcharts.Chart(options);
}
Here's some part of the code behind:
public JavaScriptSerializer javaSerial = new JavaScriptSerializer();
public string[] Names = new string[] { "Jane", "John", "Mike" };
public string[] Data = new string[] { "1,2,3", "2,4,6", "3,6,9" }
I have implemented Highcharts successfully which is working very good. My highcharts are getting live data at every 1 minute and add points which is doing as expected. But I have certain problem likes
My highcharts is having two series First is line type series and second is area type series. First series will get always 2 points only and second will get more than 200 points. As I told you my data is live, data start coming on 7 AM just for line and blank data for area until 9 AM at exact 9 AM new data will start coming at every 1 minute until 12.30 PM but what happens at 9 AM my chart goes stop and even on new next day 7 AM my chart stop
But if i refresh my browser I get new data and it will start working as we needed.
My code as follows
$(function () {
$('#container').highcharts({
credits: {
enabled: 0
},
title: {
text: null
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
minute: '%H:%M'
},
max: <%= MilliTimeStamp(_closingTime) %> ,
min: <%= MilliTimeStamp(_openingTime) %> ,
tickInterval: 0.5 * 3600 * 1000,
minorTickInterval: 0.1 * 3600 * 1000,
title: {
text: null
},
lineWidth: 1,
minorGridLineWidth: 1,
endOnTick: true,
showLastLabel: true,
gridLineWidth: 1,
labels: {
style: {
font: '7.5pt Trebuchet MS'
}
},
reversed: <%= isArabic %> // true for arabic layout and false for english layout
},
yAxis: {
title: {
text: null
},
max: <%= maxY %> ,
min: <%= minY %> ,
endOnTick: true,
showLastLabel: true,
labels: {
style: {
font: '7.5pt Trebuchet MS'
}
},
opposite: <%= isArabic %> // true for arabic layout and false for english layout
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
lineWidth: 1,
marker: {
enabled: false
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
},
line: {
lineWidth: 1,
marker: {
enabled: false
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
tooltip: {
formatter: function () {
return '<span style="font-size:7.5pt;">' + Highcharts.dateFormat('%A, %e %B, %H:%M', this.points[0].x) + '</span><br><span style="color:' + this.points[0].series.color + ';">' + this.points[0].series.name + '</span>: <b>' + Highcharts.numberFormat(this.points[0].y, 0) + '</b>';
},
useHTML: true,
shared: true
},
series: [{
type: 'area',
data: []
}, {
type: 'line',
color: 'Red',
data: []
}]
});
<%
if (isArabic == "true") { %> Highcharts.setOptions({
lang: {
months: <%= months %> ,
weekdays: <%= days %>
}
}); <%
} %>
$.ajaxSetup({
cache: false
});
recieveData();
});
function recieveData() {
var pathArray = window.location.pathname.split('/');
var chart = $('#container').highcharts();
$.ajax({
url: '/' + pathArray[1] + '/HomePageChartData.aspx',
dataType: 'json',
cache: false,
data: {
'time': new Date().getSeconds()
},
success: function (data) {
chart.yAxis[0].setExtremes(data.minY, data.maxY, true, true);
chart.series[1].setData([]);
chart.series[1].name = data.lineSeriesName;
chart.series[0].setData([]);
chart.series[0].name = data.areaSeriesName;
for (var x in data.lineSeriesData) {
chart.series[1].addPoint([data.lineSeriesData[x][0], data.lineSeriesData[x][1]]);
}
for (var x in data.areaSeriesData) {
chart.series[0].addPoint([data.areaSeriesData[x][0], data.areaSeriesData[x][1]]);
}
setTimeout(recieveData, 60000);
}
}
});
}
my JSON data at 7 AM
{"maxX":"1367843400000","minX":"1367830800000","maxY":"7912","minY":"7511","tickIntervalY":"80","lineSeriesName":"Open","areaSeriesName":"Price Index","lineSeriesData":[[1367830800000,7715.35],[1367843400000,7715.35]],"areaSeriesData":[]}
my JSON data after 9 AM
{"maxX":"1367843400000","minX":"1367830800000","maxY":"7912","minY":"7511","tickIntervalY":"80","lineSeriesName":"Open","areaSeriesName":"Price Index","lineSeriesData":[[1367830800000,7715.35],[1367843400000,7715.35]],"areaSeriesData":[[1367830831000,7740.01],[1367830897000,7735.61]]}
And it will start getting new data in areaSeriesData every 1 minutes
##Update
I found the problem that at 7 AM and 9 AM I was not getting data I was getting empty string, so it was going to error which I was not handling, now I change it as below which start removing series but now I am not getting series for line at 7 AM which have data.Can somebody tells me what I am missing or doing wrong over here.
function recieveData() {
var pathArray = window.location.pathname.split( '/' );
var chart = $('#container').highcharts();
$.ajax({
url: '/' + pathArray[1] + '/_layouts/KSE.SharePoint/HomePageChartData.aspx',
dataType: 'json',
cache: false,
data:{'time': new Date().getSeconds() },
success: function (data) {
chart.yAxis[0].setExtremes(data.minY, data.maxY, true, true);
chart.series[1].setData([]);
chart.series[1].name = data.lineSeriesName;
chart.series[0].setData([]);
chart.series[0].name = data.areaSeriesName;
for (var x in data.lineSeriesData) {
chart.series[1].addPoint([data.lineSeriesData[x][0], data.lineSeriesData[x][1]]);
}
for (var x in data.areaSeriesData) {
chart.series[0].addPoint([data.areaSeriesData[x][0], data.areaSeriesData[x][1]]);
}
setTimeout(recieveData, 60000);
},
error: function() {
setTimeout(recieveData, 60000);
}
});
}
You should parse your json to prepare separate data for series. Morever you need to use data, instead of "lineSeriesData" or "areaSeriesData". So it should looks like:
[{
data:[[1367830800000, 7715.35],
[1367843400000, 7715.35]]
},{
data:[[1367830831000, 7740.01],
[1367830897000, 7735.61]]
}]
I have a problem with jqGrid . jqGrid version 4.2.0 - jQuery Grid
grid show loaded data not in tree mode, only grid mode. Why ?
Please help me ! Можно по русски .
Add in header
<link href="../jqGrid/css/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="jqGrid/js/i18n/grid.locale-ru.js" type="text/javascript"></script>
<script src="jqGrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
and my function to get data from web service .
function getDataSC(pData) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '<%= ResolveClientUrl("~/FetchData.asmx/bindSCJson") %>',
dataType: "json",
success: function(data, textStatus) {
if (textStatus == "success")
ReceivedClientDataSC(JSON.parse(getMain(data)).rows);
},
error: function(data, textStatus) {
alert('An error has occured retrieving data!');
}
});
}
function ReceivedClientDataSC(data) {
var thegrid = $("#gridSC");
thegrid.clearGridData();
for (var i = 0; i < data.length; i++)
thegrid.addRowData(i + 1, data[i]);
}
function getMain(dObj) {
if (dObj.hasOwnProperty('d'))
return dObj.d;
else
return dObj;
}
var lastSel;
$("#gridSC").jqGrid({
datatype: function(pdata) { getDataSC(pdata); },
treeGrid: true,
treeGridModel : 'adjacency',
ExpandColumn: 'Name',
ExpandColClick: true ,
mtype: 'POST',
treeIcons: {plus:'ui-icon-circle-plus',minus:'ui-icon-circle-minus',leaf:'ui-
icon-person'},
height: "100%",
width: 900,
colNames: ['Id', 'Name', 'CountryName', 'Town', 'Adress', 'Phone', 'Email',
'Url'],
colModel: [
{ name: 'Id', index:'id', width:10, hidden:true,key:true},
{ name: 'Name', index: 'Name', width: 80},
{ name: 'CountryName',index:'CountryName', width:80},
{ name: 'Town', index: 'Town', width: 20 },
{ name: 'Adress', index: 'Adress', width: 90 },
{ name: 'Phone', index: 'Phone', width: 20},
{ name: 'Email', index: 'Email', width: 20 },
{ name: 'Url', index: 'Url', width: 30}
],
pager: $('#pjmapSC')
//rowNum:20,
//viewrecords: true,
//gridview: true,
//rowList:[10,20,30,100],
//sortname: 'Id',
//sortorder: 'asc'
})
}
json from server service (loaded to grid) :
{"d":"{\"total\":1,\"page\":1,\"records\":2,\"rows\":[{\"err\":null,\"Id\":1,\"Parent
\":0,\"Name\":\"Сервисные центры\",\"CountryCode\":103,\"Town\":\"Киев\",\"Adress
\":\"Красных партизан 1\",\"Phone\":\"123-321\",\"Email\":\"mail#mail.ru
\",\"CountryName\":\"United Arab Emirates\",\"Url\":\"www.service1\",\"isLeaf\":false,
\"Expanded\":true,\"Level\":1},{\"err\":null,\"Id\":2,\"Parent\":1,\"Name
\":\"Сервисный центр 1_1\",\"CountryCode\":103,\"Town\":\"Киев\",\"Adress\":\"Артема
\",\"Phone\":\"123-321\",\"Email\":\"fert#ukr.net\",\"CountryName\":\"United Arab
Emirates\",\"Url\":\"www.service2\",\"isLeaf\":true,\"Expanded\":true,\"Level\":2}],
\"userData\":null}"}
Help Please ! Thanks.
EDIT:
Thanks Oleg , but i try change my server string to
{"d":{"__type":"_admin.JqGridData","total":3,"page":1,"records":26,"rows": [{"id":1,"cell":["1","Сервисные центры","United Arab Emirates","Киев","Красных партизан 1","123-321","mail#mail.ru","www.service1","0",null,"False","False"]},{"id":2,"cell":["2","Сервисный центр 1_1","United Arab Emirates","Киев","Артема","123-321","fert#ukr.net","www.service2","1","1","True","False"]},{"id":4,"cell":["4","Сервисный центр 1_2","United Arab Emirates","Донецк","Артема","123-321","fert#ukr.net","www.service2","1","1","True","False"]},{"id":5,"cell":["5","Сервисный центр 1_3","United Arab Emirates","Одесса","Артема","123-321","fert#ukr.net","www.service3","1","1","True","False"]},
and
$("#gridSC").jqGrid({
url: '<%= ResolveClientUrl("~/FetchData.asmx/bindSC") %>',
datatype: 'json',
mtype: 'POST',
treeGridModel: 'adjacency',
ExpandColumn: 'Name',
ExpandColClick: true,
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
//if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj.d.rows; },
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; }
},
colNames: ['Id', 'Name', 'CountryName', 'Town', 'Adress', 'Phone', 'Email', 'Url'],
colModel: [
{ name: 'Id', index: 'id', width: 10, hidden: true, key: true },
{ name: 'Name', index: 'Name', width: 80 },
{ name: 'CountryName', index: 'CountryName', width: 80 },
{ name: 'Town', index: 'Town', width: 20 },
{ name: 'Adress', index: 'Adress', width: 90 },
{ name: 'Phone', index: 'Phone', width: 20 },
{ name: 'Email', index: 'Email', width: 20 },
{ name: 'Url', index: 'Url', width: 30 }
],
rowNum: 10,
rowList: [10, 20, 300],
sortname: 'Name',
sortorder: "asc",
pager: "#pjmapSC",
viewrecords: true,
gridview: true,
rownumbers: true,
height: "100%",
caption: ''
})
and test
treeReader : {
level_field: "level",
parent_id_field: "parent",
leaf_field: "isLeaf",
expanded_field: "expanded"
},
nothing change in grid (not tree grid) . In server side my method
int startIndex = (page - 1) * rows;
int endIndex = (startIndex + rows < recordsCount) ?
startIndex + rows : recordsCount;
List<TableRow> gridRows = new List<TableRow>(rows);
for (int i = startIndex; i < endIndex; i++)
{
gridRows.Add(new TableRow()
{
id = lsc[i].Id,
cell = new List<string>(11) {
lsc[i].Id.ToString(),
lsc[i].Name,
lsc[i].CountryName,
lsc[i].Town,
lsc[i].Adress,
lsc[i].Phone,
lsc[i].Email,
lsc[i].Url,
lsc[i].level.ToString(),
lsc[i].parent,
lsc[i].isLeaf.ToString(),
lsc[i].expanded.ToString()
if i change to this
//string.Format("Name:{0}", lsc[i].Name)
my grid load incorrectly data
Help please.
Thanks Oleg , but i try change my server string to
{"d":{"__type":"_admin.JqGridData","total":3,"page":1,"records":26,"rows": [{"id":1,"cell":["1","Сервисные центры","United Arab Emirates","Киев","Красных партизан 1","123-321","mail#mail.ru","www.service1","0",null,"False","False"]},{"id":2,"cell":["2","Сервисный центр 1_1","United Arab Emirates","Киев","Артема","123-321","fert#ukr.net","www.service2","1","1","True","False"]},{"id":4,"cell":["4","Сервисный центр 1_2","United Arab Emirates","Донецк","Артема","123-321","fert#ukr.net","www.service2","1","1","True","False"]},{"id":5,"cell":["5","Сервисный центр 1_3","United Arab Emirates","Одесса","Артема","123-321","fert#ukr.net","www.service3","1","1","True","False"]},
and
$("#gridSC").jqGrid({
url: '<%= ResolveClientUrl("~/FetchData.asmx/bindSC") %>',
datatype: 'json',
mtype: 'POST',
treeGridModel: 'adjacency',
ExpandColumn: 'Name',
ExpandColClick: true,
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
//if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj.d.rows; },
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; }
},
colNames: ['Id', 'Name', 'CountryName', 'Town', 'Adress', 'Phone', 'Email', 'Url'],
colModel: [
{ name: 'Id', index: 'id', width: 10, hidden: true, key: true },
{ name: 'Name', index: 'Name', width: 80 },
{ name: 'CountryName', index: 'CountryName', width: 80 },
{ name: 'Town', index: 'Town', width: 20 },
{ name: 'Adress', index: 'Adress', width: 90 },
{ name: 'Phone', index: 'Phone', width: 20 },
{ name: 'Email', index: 'Email', width: 20 },
{ name: 'Url', index: 'Url', width: 30 }
],
rowNum: 10,
rowList: [10, 20, 300],
sortname: 'Name',
sortorder: "asc",
pager: "#pjmapSC",
viewrecords: true,
gridview: true,
rownumbers: true,
height: "100%",
caption: ''
})
and test
treeReader : {
level_field: "level",
parent_id_field: "parent",
leaf_field: "isLeaf",
expanded_field: "expanded"
},
nothing change in grid (not tree grid) . In server side my method
int startIndex = (page - 1) * rows;
int endIndex = (startIndex + rows < recordsCount) ?
startIndex + rows : recordsCount;
List<TableRow> gridRows = new List<TableRow>(rows);
for (int i = startIndex; i < endIndex; i++)
{
gridRows.Add(new TableRow()
{
id = lsc[i].Id,
cell = new List<string>(11) {
lsc[i].Id.ToString(),
lsc[i].Name,
lsc[i].CountryName,
lsc[i].Town,
lsc[i].Adress,
lsc[i].Phone,
lsc[i].Email,
lsc[i].Url,
lsc[i].level.ToString(),
lsc[i].parent,
lsc[i].isLeaf.ToString(),
lsc[i].expanded.ToString()
if i change to this
//string.Format("Name:{0}", lsc[i].Name)
my grid load incorrectly data
Help please.
You main error is in the wrong case of the column names of Tree Grid which you use. It should be level, parent, expanded instead of Level, Parent, Expanded which you use in the JSON input. Only isLeaf you use correctly. So you should either correct the column which use your web service or add parameter treeReader which describes the names which you use:
treeReader = {
level_field: "Level",
parent_id_field: "Parent",
leaf_field: "isLeaf",
expanded_field: "Expanded"
}
Additionally I would recommend you to change your code so that you use datatype: 'json' instead of datatype as function.