Highcharts column + line combination chart with multiple series - javascript

In my graph I want to add both column graph and line graph(trendline) for count . My code is like this
var crime_data=[];
for(var i=0;i<result.themes.length;i++){
var crime={};
var test2 = result.themes[i];
var test = test2[Object.keys(test2)];
console.log("test",test);
crime.name = Object.keys(result.themes[i]);
crime.data = [];
var test1 = test.individualValueVariable;
for(var j=0;j<test1.length;j++){
crime.data.push(test1[j].count);
};
crime_data.push(crime);
};
var crimeChart = new Highcharts.Chart({
chart: {
renderTo: 'container1',
type: 'colomn'
},
xAxis: {
categories:year,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Count'
}
},
credits: {
enabled: false
},
tooltip: {
shared: true,
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0,
depth: 25,
allowPointSelect: true,
cursor: 'pointer',
point: {
},
}
},
series:crime_data
});
If I add type 'spline ' in series. I am not getting even data and not trend line. Please suggest me how should i add trend line in this case.
And this is my JSON :
{
"boundaries": {
"boundary": [{
"boundaryId": "45083021025",
"boundaryType": "USA_POSTCODE",
"boundaryRef": "B1"
}]
},
"themes": [{
"TheftCrimeTheme": {
"boundaryRef": "B1",
"individualValueVariable": [{
"name": "2012 Theft Crime",
"description": "Theft Crime for 2012",
"count": 310
}, {
"name": "2013 Theft Crime",
"description": "Theft Crime for 2013",
"count": 230
}]
}
}, {
"AssaultCrimeTheme": {
"boundaryRef": "B1",
"individualValueVariable": [{
"name": "2012 Assault Crime",
"description": "Assault Crime for 2012",
"count": 50
}, {
"name": "2013 Assault Crime",
"description": "Assault Crime for 2013",
"count": 41
}]
}
}]
}
Please suggest me how should I do this.

Highcharts does not have trendline functionality built in. You can use something like: https://github.com/virtualstaticvoid/highcharts_trendline
to calculate your trendline values and pass it as to new line series.

Related

Kendo Pie chart implementaion

I am creating a project using JavaScript with Kendo. I am the beginner in Kendo.
I have problem while integrating the pie chart.I want to this type of chart:
But when I integrate the code according to reference site then my chart shapes become:
Here is the code:
<div id="example">
<div class="demo-section k-content wide">
<div id="chart"></div>
</div>
<script>
var data = [
{
"source": "Hydro",
"percentage": 22,
"explode": true
},
{
"source": "Solar",
"percentage": 2
},
{
"source": "Nuclear",
"percentage": 49
},
{
"source": "Wind",
"percentage": 27
}
];
function createChart() {
$("#chart").kendoChart({
title: {
text: "Break-up of Spain Electricity Production for 2008"
},
legend: {
position: "bottom"
},
dataSource: {
data: data
},
series: [{
type: "pie",
field: "percentage",
categoryField: "source",
explodeField: "explode"
}],
seriesColors: ["#03a9f4", "#ff9800", "#fad84a", "#4caf50"],
tooltip: {
visible: true,
template: "${ category } - ${ value }%"
}
});
}
$(document).ready(createChart);
$(document).bind("kendo:skinChange", createChart);
</script>
</div>
Add this to your definition to remove shadow and border and keep the same skin
seriesDefaults: {
overlay: { gradient: "none" },
border: {
width: 0,
color: ""
}
}
If your problem is only with the styling, you can set your chart theme. Just add theme: "material" and you should get a plain color.
A list of themes can be found on kendo UI docs https://docs.telerik.com/kendo-ui/styles-and-layout/appearance-styling

How to show stacked and unstacked bar graphs together in Chart.js

We are trying to display three sets of data, two stacked, one unstacked using chart.js. We defined two sets of axis where only the stacked data shows and the unstacked data does not. We can only get the axis to display or not display, but we cannot get the data to appear at all.
We know the data is valid because we can get all of the data to stack together, but not separately.
recycleChartData = {
"type":"bar",
"data":{
"labels":["Mar-2016"],
"datasets":[
{
"label":"benchmark",
"backgroundColor":"#ff3300",
"yAxisID":"stacked_testY2",
"xAxisID":"stacked_testX2",
"data":["2632.29"]
},
{
"label":"Crossville",
"backgroundColor":"#009900",
"yAxisID":"stacked_testY",
"xAxisID":"stacked_testX",
"data":["2268.44"]
},
{
"label":"test",
"backgroundColor":"#ffff00",
"yAxisID":"stacked_testY",
"xAxisID":"stacked_testX",
"data":["181.92"]
}
]
},
"options":{
"scales":{
"yAxes":[
{
"id":"stacked_testY",
"position":"left",
"stacked":true,
"display":true
},
{
"id":"stacked_testY2",
"position":"left",
"stacked":false,
"display":false
}
],
"xAxes":[
{
"id":"stacked_testX",
"position":"bottom",
"stacked":true,
"display":true
},
{
"id":"stacked_testX2",
"position":"bottom",
"stacked":false,
"display":false
}
]
}
}
};
It's odd that your code doesn't work, if you change the non-stacked dataSet to a line graph you see the data! Maybe worth posting an issue on the chartjs github.
But...
There was a feature released in 2.5.0 which will allow for this sort of scenario. More on what it is can be read here, https://github.com/chartjs/Chart.js/issues/2643.
Basically, you can add a new property stack on each of your dataSets to denote which stack you would like it to go on to, so for example with your data you could remove the extra scales and have 2 stacks
var config = {
"type": "bar",
"data": {
"labels": ["Mar-2016","Apr-2016"],
"datasets": [ {
"label": "Crossville",
"backgroundColor": "#009900",
"data": ["2268.44","2268"],
stack: 2,
}, {
"label": "test",
"backgroundColor": "#ffff00",
"data": ["181.92","181.92"],
stack: 2
},{
"label": "benchmark",
"type": "bar",
"backgroundColor": "#ff3300",
"data": ["2632.29","2632.29"],
stack: 1
}]
},
"options": {
"scales": {
"yAxes": [{
"id": "stacked_testY",
"type": 'linear',
"position": "left",
"stacked": true,
"display": true
}],
"xAxes": [{
"position": "bottom",
"stacked": true,
"display": true
}]
}
}
};
var chartElement = document.getElementById('chart');
var chart = new Chart(chartElement, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<div style="width:75%;">
<canvas id="chart"></canvas>
</div>
I came across this issue when trying to find out how to stack specific datasets of a line diagram in Chart.js v2.x.
Chart.js v3.x supports the stack attribute for line diagrams but in Chart.js v2.x:
you have to use multiple y-axis
to align the values you need to calculate the maximal value yourself and set ticks.max or ticks.suggestedMax in the axis configuration.
false console:
let yMax = 3000; // Calculate value beforehand.
var config = {
"type": "line",
"data": {
"labels": ["Mar-2016","Apr-2016","May-2016"],
"datasets": [ {
"label": "Crossville",
"backgroundColor": "#009900",
"data": ["2268.44","2268","31"]
}, {
"label": "test",
"borderColor": "#ffff00",
"data": ["181.92","181.92", "1000"],
"yAxis": 'A'
},{
"label": "benchmark",
"backgroundColor": "#ff3300",
"data": ["2632.29","2632.29","500"]
}]
},
"options": {
"scales": {
"yAxes": [
{
"id": "A",
ticks: {
beginAtZero: true,
display: true,
suggestedMax: yMax
},
},
{
"stacked": true,
"ticks": {
beginAtZero: true,
display: true, // Set this to false so that only one axis is shown!!!
suggestedMax: yMax
},
},
],
"xAxes": [{
"position": "bottom",
"stacked": true,
"display": true
}]
}
}
};
var chartElement = document.getElementById('chart');
var chart = new Chart(chartElement, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<div style="width:75%;">
<canvas id="chart"></canvas>
</div>

Working with JSONP Object in Highcharts

I have working JSONP being passed from my server. The JSONP (with the $.getJSON padding) looks like this:
jQuery21009647691948339343_1398527630522([
{
"name": 'World Federation of Democratic Youth',
"data": [16]
},
{
"name": 'Poqilet',
"data": [13]
},
{
"name": 'United Society',
"data": [8]
},
{
"name": 'Japvia',
"data": [589]
},
{
"name": 'the Mars',
"data": [1]
},
{
"name": 'The Americas',
"data": [913]
},
{
"name": 'High Orion Alliance',
"data": [1]
}
])
The PHP script I am using to pass this to my client is this:
header("content-type: application/json");
$array = (file_get_contents('data.json'));
echo $_GET['callback']. '('. ($array) . ')';
Now, when I get this object I want to put it into a Highcharts series
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Update Order'
},
xAxis: {
categories: ['Regions']
},
yAxis: {
min: 0,
title: {
text: 'Number of Nations'
}
},
legend: {
backgroundColor: '#FFFFFF',
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{}]
};
var url = "http://myserver.org/requestjsonp.php?callback=?";
$.getJSON(url, function (data) {
console.log(data);
options.series.data = data;
var chart = new Highcharts.Chart(options);
});
});
This is not working and I do not understand why, as I have worked through the errors I was getting before. Now I get no errors in the console, I just get nothing.
If I paste the contents of the JSON into the series, I get what I want, although I have to take out the first "{" and the last "}" character. Is this the problem? How can I remove them from an object if they are required to be in the JSON so that it can get passed to the client?
.remove() and other jquery methods I tried to trim the data once I received it didn't work.
console.log(data) now provides an array of 7 objects, which I believe is in line with data.json (seven name/data pairs).
Thank you for your consideration! :)
Your JSONP is incorrect. Without the padding it would look like:
{
name: 'World Federation of Democratic Youth',
data: [16]
},
{
name: 'Poqilet',
data: [13]
},
This is not valid JSON. It should probably look like:
[{
"name": "World Federation of Democratic Youth",
"data": [16]
},
{
"name": "Poqilet",
"data": [13]
}]
You probably also just want to do options.series = data since data will be an array.
In your JSON you have structre of series, not points. Because you use data[] paramter inside. In other words it should be:
options.series = data;
It turns out the JSONP data was not formatted correctly for Highcharts, so what I did was made it look like this (with padding):
jQuery21009184384981635958_1398737380163([{"name": "Regions","data": ["World Federation of Democratic Youth", "Poqilet", "United Society", "Japvia", "the Mars", "The Americas", "High Orion Alliance"]},{"name": "Number of Nations","data": [16, 13, 5, 566, 1, 926, 1]}])
And the Javascript to utilize it:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Update Order',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Number of Nations'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON('http://myserver.org/requestjsonp.php?callback=?', function(data) {
options.xAxis.categories = data[0]['data'];
options.series[0] = data[1];
chart = new Highcharts.Chart(options);
});
});
This works for the small JSONP excerpt that I posted, but not for my full set of data, which contains over 10,000 values and was throwing up a Highcharts Error 19 (http://www.highcharts.com/errors/19) message, so I will be trying to do a master-detail chart to deal with the large amount of data, but this should work for you if you have a small dataset.
For more on how highcharts data should be formatted, you can go here: http://www.highcharts.com/docs/chart-concepts/series/#1

Need some pointers regarding JSON formatting for Highcharts

I have the following JSON that I am trying to use for a highcharts chart. Current I get nothing output in the chart (data), although I do see all four "questions" in the legend.
[
{
"name": "Question 1",
"data": [
"1391981824000, 2",
"1391981874000, 2",
"1391981966000, 4",
"1391982000000, 1"
]
},
{
"name": "Question 2",
"data": [
"1391981830000, 3",
"1391981878000, 4",
"1391981971000, 2",
"1391982005000, 2"
]
},
{
"name": "Question 3",
"data": [
"1391981837000, 1",
"1391981885000, 1",
"1391981977000, 1",
"1391982010000, 3"
]
},
{
"name": "Question 4",
"data": [
"1391981842000, 4",
"1391981898000, 3",
"1391981982000, 3",
"1391982015000, 4"
]
}
]
And the javascript for the chart:
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("mysql/getChartData.php?sd=2012-02-09%2015:36:42&ed=2016-02-09%2016:37:39", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'custom-range-line',
type: 'line'
},
xAxis: {
type: 'datetime'
},
title: {
text: 'Custom Date Range',
x: -20
},
subtitle: {
text: '',
x: -20
},
yAxis: {
title: {
text: 'Number of Ratings'
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 2
},
series: json
});
});
});
});
What am I doing wrong/why wouldn't this work? I've found a ton of example of how to do this, but none quite the way I need it. Let me know if there's anything else I can show.
Your data needs to be an array of tuples like so: For the UNIX timestamps, they need to be numeric, you currently have them as strings. It looks like you have correctly multiplied the UNIX timestamp * 1000 in order to work in JavaScript. Be assured that the value of options.data is an array so you can add more sets to it. Try it with one first, then gradually increase it so you can get used to the HighCharts API.
var options = {
"data": {[
[1391981824000, 2],
[1391981874000, 2],
[1391981966000, 4],
[1391982000000, 3],
]}
}

HighCharts: Logarithmic Scale for Horizontal Bar Charts

I am working with HighCharts to produce a bar chart. My values can range from as minimal as 0 to as high as 100k (example). Therefore, one bar of the graph can be very small and the other can be very long. HighCharts has introduced the feature of "Logarithmic Scaling". The example of which can be seen HERE
My js code is written in this jsfiddle file. I want to display my horizontal axis (x-Axis) logarithmically. I have inserted the key type as shown in the example but the script goes into an infinite loop which has to be stopped.
What is the flaw in the execution or is logarithmic scaling for HighCharts still not mature?
P.S The commented line in jsfiddle is causing the issue
Since the "official" method is still buggy, you can achieve the log scale more manually by manipulating your input data with a base 10 log and masking your output data raising 10 to the output value. See it in action here http://jsfiddle.net/7J6sc/ code below.
function log10(n) {
return Math.log(n)/Math.log(10);
}
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'bar',
marginRight: 200,
marginLeft: 10,
},
title: {
text: 'Negative'
},
xAxis: {
categories: [''],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: '',
align: 'high',
},
labels: {
formatter: function() {
return Math.round(Math.pow(10,this.value));
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -50,
y: 100,
floating: true,
borderWidth: 1,
shadow: true
},
tooltip: {
formatter: function() {
return '' + this.series.name + ': ' + Math.round(Math.pow(10,this.y)) + ' millions';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function() {
return Math.round(Math.pow(10,this.y));
}
}
}
},
credits: {
enabled: false
},
series: [{
"data": [log10(4396)],
"name": "A"},
{
"data": [log10(4940)],
"name": "B"},
{
"data": [log10(4440)],
"name": "C"},
{
"data": [log10(2700)],
"name": "D"},
{
"data": [log10(2400)],
"name": "E"},
{
"data": [log10(6000)],
"name": "F"},
{
"data": [log10(3000)],
"name": "G"},
{
"data": [log10(15000)],
"name": "E"}],
});
It is still experimental according to the Official Documentation, so that might be the case:
"The type of axis. Can be one of "linear" or "datetime". In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days.
As of 2.1.6, "logarithmic" is added as an experimental feature, but it is not yet fully implemented. Defaults to "linear".
Try it: "linear", "datetime" with regular intervals, "datetime" with irregular intervals, experimental "logarithmic" axis."
For those of you who are still looking for an answer :
JSFiddle : http://jsfiddle.net/TuKWT/76/
Or SO snippet :
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'bar'
},
title: {
text: 'Negative'
},
xAxis: {
categories: ['A','B','C','D','E','F','G','H'],
title: {
text: null
}
},
yAxis: {
type: 'logarithmic',
//min: 0, <= THIS WILL CAUSE ISSUE
title: {
text: null,
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return this.x + ':' + this.y + ' millions';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: false
}
}
},
credits: {
enabled: false
},
series: [{
"data": [4396,4940,4440,2700,2400,6000,3000,15000],
}],
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>

Categories

Resources